回调函数后 Angular2 视图未更新
Angular2 view not updated after callback function
我正在使用 Meteor-Angular2 和 slingshot 包将图像上传到 S3 存储。从函数返回并分配给绑定字符串时,视图未更新。 (setTimout 函数正在工作并更新视图,但上传器函数没有)
export class AdminComponent {
public urlVariable: string = "ynet.co.il";
constructor() {
this.uploader = new Slingshot.Upload("myFileUploads");
setTimeout(() => {
this.urlVariable = "View is updated";
}, 10000);
}
onFileDrop(file: File): void {
console.log('Got file2');
this.uploader.send(file, function (error, downloadUrl) {
if (error) {
// Log service detailed response
}
else {
this.urlVariable = "View not updated";
}
});
}
}
使用箭头函数 (() =>
) 而不是 function ()
来保留 this.
的范围
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this.urlVariable = "View not updated";
}
});
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
这个对我有用:(窄函数+Ngzone)
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this._ngZone.run(() => {this.urlVariable = "View not updated"; });
}
});
我正在使用 Meteor-Angular2 和 slingshot 包将图像上传到 S3 存储。从函数返回并分配给绑定字符串时,视图未更新。 (setTimout 函数正在工作并更新视图,但上传器函数没有)
export class AdminComponent {
public urlVariable: string = "ynet.co.il";
constructor() {
this.uploader = new Slingshot.Upload("myFileUploads");
setTimeout(() => {
this.urlVariable = "View is updated";
}, 10000);
}
onFileDrop(file: File): void {
console.log('Got file2');
this.uploader.send(file, function (error, downloadUrl) {
if (error) {
// Log service detailed response
}
else {
this.urlVariable = "View not updated";
}
});
}
}
使用箭头函数 (() =>
) 而不是 function ()
来保留 this.
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this.urlVariable = "View not updated";
}
});
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
这个对我有用:(窄函数+Ngzone)
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this._ngZone.run(() => {this.urlVariable = "View not updated"; });
}
});