我在使用 TypeScript 时遇到了 Angular 2 的问题,我需要额外的关注。我正在从一个效果很好的 API 请求一个 token 。在我的响应处理程序中,我检查基本错误并将其显示给最终用户。如果我从控制台注销错误和消息,它会正确显示,但 View /模板不会更新。
在我的类里面,我有以下内容:
public message: string;
在我的构造函数中,我有:
constructor() {
this.message = 'Message to enduser';
}
我的两种方法如下:
myRequest() {
(<any>window).privateAPI.getToken({
token: this.tmpData.token
}, this.responseHandler);
return false;
}
responseHandler(response: any) {
setTimeout(function() {
if (response.error) {
// this.message update is not updating in the template
this.message = response.error.message;
console.log('error: ', this.message);
} else {
// success
}
}, 100);
}
任何帮助将不胜感激。
最佳答案
我能够通过使用 ngZone 解决这个问题。以下解决了我的组件未更新 API 响应中的模板的问题。
// import NgZone
import {Component, NgZone} from '@angular/core';
// pass NgZone to constructor
constructor(private _zone: NgZone) {
this.message = 'Message to enduser';
}
requestToken() {
(<any>window).privateAPI.getToken({
token: this.tmpData.token
}, (status: number, response: any) => {
this._zone.run(() => {
if (response.error) {
this.message = response.error.message;
} else {
// good to go
}
});
});
}
关于javascript - Angular 2 与 TypeScript : View not updating after setting variable in response handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186328/