我是 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>
当我点击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/