javascript - 与组件属性隔离的回调

标签 javascript cordova angular typescript

我是 TypeScript 和 Angular 2 的新手。

我在使用 Cordova 相机插件时遇到了一个奇怪的问题:当我拍照时,回调似乎与组件的其余部分隔离!

这里是代码:

结果.component.ts

import {Component, OnInit} from "@angular/core";

@Component({
    moduleId: module.id,
    selector: 'app-result',
    templateUrl: 'result.component.html'
})
export class ResultComponent implements OnInit {
    pictureSource;
    destinationType;
    status = 0; //VALUE I WANT TO PRINT

    constructor() {
        this.pictureSource = navigator.camera.PictureSourceType;
        this.destinationType = navigator.camera.DestinationType;
    }

    ngOnInit(): void {

    }

    test() {
        console.log(this.status); //VALUE I PRINT
    }

    capturePicture() {
        let cameraOptions = {
            quality: 100,
            destinationType: this.destinationType.FILE_URI
        };
        navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFail, cameraOptions);
    }

    onCaptureSuccess(fileURI: string): void {
        console.log(this.status); //THROW ERROR
    }

    onCaptureFail(error: string): void {
        console.log('error', error);
    }
}

result.component.html

<div>
    <h1>Photo</h1>

    <button (click)="capturePicture()">PHOTO</button>
    <button (click)="test()">TEST</button>
</div>

控制台输出: Console output

当我点击TEST 按钮(在此屏幕截图中点击 8 次)时,我得到了可以正常工作的 console.log。 然后,当我点击PHOTO按钮,拍照并返回时,我得到Cannot read property 'status' of null 然后,我点击 TEST 按钮 4 次,状态值出现......

看起来 navigator.camera.getPicture 的回调与组件的其余部分是隔离的,我们该如何解释?

最佳答案

我从未使用过 Angular 或 Cordova,但它看起来像是简单地丢失了这个上下文。 Angular 的点击处理程序确实尊重组件上下文。但在这条线上...

navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFail, cameraOptions);

...您只需移交对函数的引用,getPicture 无法了解您的上下文。解决此问题的一种方法是绑定(bind) this:

navigator.camera.getPicture(this.onCaptureSuccess.bind(this), this.onCaptureFail, cameraOptions);

或者使用箭头函数,或者用闭包自己缓冲this,或者...

关于javascript - 与组件属性隔离的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39417194/

相关文章:

javascript - 如何转义字符并同时将变量放入 Json - Javascript

ionic-framework - 如何从 Ionic2 中的 ionic 输入获取包装输入?

当数据服务控制台记录数据正常时,Angular2 解析器返回 undefined

javascript onclick 调用函数

javascript - 使用括号时,Angularjs 有时会解析错误

cordova - 即使安装了插件,也会出现安装 FCM 插件的问题

ios - 如何从IOS浏览器播放SWF动画文件?

java - Apache Cordova 媒体捕获插件不显示视频记录倒计时时间

javascript - 使用filter()时RxJS延迟更新下一个值

javascript - 使用每个主干同步请求发送 token