服务成功后在组件中获取未定义

时间:2018-04-03 16:57:25

标签: angular asp.net-web-api

我正在使用Angular 5登录,所以在我的服务中我有

login(email: string, password: string) {
    debugger;
    return this.http.post('http://localhost:58607/api/account/Login', JSON.stringify({ email: email, password: password }), { headers: new Headers({ 'Content-Type': 'application/json' }) })
      .map((response: Response) => {
        // login successful if there's a jwt token in the response
        let user = response.json();
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }
      });
  }

和typescript组件我有类似的东西:

signin() {
    this.loading = true;

    this._authService.login(this.model.email, this.model.password).subscribe(
      data => {
        this._router.navigate([this.returnUrl]);
      },
      error => {
        this.showAlert('alertSignin');
        this._alertService.error(error._body);
        this.loading = false;
      });
  }

问题是当我调试时,当调试器到达组件时,data未定义为下一张图片:

enter image description here

有人知道那里发生了什么,服务是否正确执行状态200,但我不知道为什么我收到未定义的组件?此致

1 个答案:

答案 0 :(得分:1)

正如我在评论中所提到的,你必须在map函数中返回:

login(email: string, password: string) {
    debugger;
    return this.http.post('http://localhost:58607/api/account/Login', JSON.stringify({ email: email, password: password }), { headers: new Headers({ 'Content-Type': 'application/json' }) })
      .map((response: Response) => {
        // login successful if there's a jwt token in the response
        let user = response.json();
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          /** RETURN **/
          return user;
        }
      });
  }