鍍金池/ 問答/HTML5  網(wǎng)絡安全/ httpclient.subcribe不返回結果(請求以經(jīng)401),導致一直在l

httpclient.subcribe不返回結果(請求以經(jīng)401),導致一直在loading

圖片描述
圖片描述

回答
編輯回答
孤星

你代碼寫的有問題,網(wǎng)絡請求是異步的。應該在獲取數(shù)據(jù)后才設置loading的值。

this.loading=true;
this.login.subscribe(
   success =>{
     this.loading=false;
},
   error=>{
     this.loading=false;
}
);
2017年1月18日 17:08
編輯回答
孤島

你的login()這個方法寫的有問題,
首先你return的errorMesg肯定是null,http請求是異步的,你在return的時候,請求未必已經(jīng)完成了。
所以你的login方法應該返回observable,這樣你就可以在login的訂閱中設置loading狀態(tài),或者其他的功能。

所以login方法應該這樣寫:

private errorMsg = null;

login(user: User): Obserable<string> {
   return this.http.post<User>(url: ..., formData).map((data: any) => {
       if (data) {
          ....
       }
       return null;
   });
}

然后在submit方法里面這樣調(diào)用

submit() {

.....
this.loading = true;
this.login(user)
   .finally(() => this.loading = false) //finally方法,不管成功或error都會設置loading為false
   .subscribe(
    (msg: any)=>  { this.errorMsg = null; },
    (error: Error) = { this.errorMsg = "用戶名或密碼不正確"; }
);
}
2017年3月29日 08:16