2 个回答

你的login()这个方法写的有问题,
首先你return的errorMesg肯定是null,http请求是异步的,你在return的时候,请求未必已经完成了。
所以你的login方法应该返回observable,这样你就可以在login的订阅中设置loading状态,或者其他的功能。

所以login方法应该这样写:

private errorMsg = null;

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

然后在submit方法里面这样调用

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 = "用户名或密码不正确"; }
);
}

你代码写的有问题,网络请求是异步的。应该在获取数据后才设置loading的值。

this.loading=true;
this.login.subscribe(
   success =>{
     this.loading=false;
},
   error=>{
     this.loading=false;
}
);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进