将HttpClient响应转换为布尔值

时间:2019-08-15 09:53:45

标签: angular rxjs angular-httpclient

我正在使用authService来调用后端端点进行身份验证,并且我想简单地将true / false返回给另一个组件,以便显示/隐藏错误消息。最重要的是,成功之后,我要将令牌存储在localStorage中。

signIn = (signInFormValue) => {
    var response = this.authService.authenticate(signInFormValue.username, signInFormValue.password)
      if(response) {      
        console.log(response)
        this.invalidCredentials = false;
      } else {
        this.invalidCredentials = true;
      }      
  }

哪个叫这个

authenticate(username: string, password: string) {
    return this.callAuthenticationEndpoint(username, password).pipe(map(res =>{
      localStorage.setItem('token', res.headers.get('Authorization');
      return true;
    }, err => {return false}))
  }

  callAuthenticationEndpoint(username: string, password: string): Observable<any> {
    var url = this.AUTHENTICATE_URL + 'username=' + username + '&password=' + password;
    return this.http.get(url, {observe: "response"});
  }

问题是response不是对/错,但是是

enter image description here

1 个答案:

答案 0 :(得分:1)

您从服务中收到的是可观察的。要获得所需的布尔响应,您必须订阅此Observable:

signIn(signInFormValue){
 return this.authService
        .authenticate(signInFormValue.username, signInFormValue.password)
        .subscribe(response => console.log(response));
}