为HttpClient.post返回一个Observable <boolean>而不是Observable <httpresponse>

时间:2017-10-30 14:33:08

标签: angular

如何在我的方法中返回Observable<boolean>而不是Observable<HttpClient<AuthResponse>>

我有这段代码:

  login(username: string, password: string) {
    const body = {username: username, password: password};
    return this.http.post<AuthResponse>(`${this.baseUrl}`, body, { observe: 'response' })
      .subscribe(response => {
        const user = response.body;
        if (user && user.token) {
          localStorage.setItem(this.localStorageKey, JSON.stringify(user));
          return true;
        }

        localStorage.removeItem(this.localStorageKey);
        return false;
      });
  }

1 个答案:

答案 0 :(得分:0)

使用map运算符并返回observable。

login(username: string, password: string) {
  const body = {username: username, password: password};
  return this.http.post<AuthResponse>(`${this.baseUrl}`, body, { observe: 'response' }).map(response => {
    const user = response.body;
    if (user && user.token) {
       localStorage.setItem(this.localStorageKey, JSON.stringify(user));
      return true;
    }

    localStorage.removeItem(this.localStorageKey);
    return false;
  });
}