[英]Angular2 this is null in component
我期望組件中“ this”為null的一些怪異情況。 到目前為止,我在兩種情況下看到了它:
1)當諾言被拒絕時:
if (this.valForm.valid) {
this.userService.login(value).then(result => {
if(result.success){
this.toasterService.pop("success", "Exito", "Inicio de session correcto");
this.sessionService.setUser(result.data);
this.router.navigateByUrl('home');
}
else{
this.error = result.code;
}
},function(error){
console.log("ERROR: " + error);
this.error = "ERROR__SERVER_NOT_WORKING";
console.log(this.error);
});
}
在函數(錯誤)中,該參數為null,因此我無法分配相應的錯誤。
該服務以以下方式工作:
login(login : Login) : Promise<Response> {
return this.http
.post(this.serverService.getURL() + '/user/login', JSON.stringify(login), {headers: this.headers})
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
因此,在調用服務handleError時,此值將丟失。
2) -使用sweetalert
logout(){
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function() {
this.sessionService.clearSession();
this.router.navigateByUrl('login');
}, function(){
//Cancel
});
}
在這里,當我確認並嘗試執行clearSession時,它為null。
我不知道這是兩個不同的問題還是兩個都是同一問題引起的。
使用() => {}
(ES6箭頭函數)作為回調,以便this
函數引用組件,因為arrow函數不會創建自己的this
上下文:
this.userService.login(value).then(
(result) => {
this.toasterService.pop("success", "Exito", "Login successful!");
},
(error) => {
// now 'this' refers to the component class
this.error = "SERVER_ERROR";
}
);
不過,如果您想使用function(){}
,則可以將組件的this
上下文綁定到回調函數,如下所示:
this.userService.login(value).then(
function(result) {
this.toasterService.pop("success", "Exito", "Login successful!");
}.bind(this),
function(error) {
// now 'this' refers to the component class
this.error = "SERVER_ERROR";
}.bind(this)
);
第二個用例也應如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.