为什么我的可观察到的返回null?

时间:2018-08-24 22:34:54

标签: angular

我有以下方法:

  public login(username: string, password: string): Observable<any> {
    console.log('Sending the login credentials to obtain a token');
    const credentials = { 'email' : username, 'password' : password };
    const url: string = environment.USER_REST_URL + '/login';
    return this.httpClient.post<any>(url, credentials);
  }

它的调用者是:

  login(): void {
    // this.keycloakClientService.login(this.username, this.password).subscribe(
    this.userRestService.login(this.username, this.password).subscribe(
      data => {
        this.authService.setJwtTokenToLocalStorage(data.token);
        this.router.navigate(['user']);
      },
      error => {
        console.log(error);
      }
    );
  }

但是数据为空。但是服务器返回了一个响应。

error块不起作用,流程进入data块。

我在Angular 6.0.4下。

更新: 错误更简单,完全是我的错误:服务器响应为空,因为它的内容只是响应Authorization标头中设置的令牌。

如何在响应对象中包含响应头

const credentials = { 'email' : username, 'password' : password };
// Have the response headers included in the response object
const options = {
  observe: 'response' as 'body'
};
const url: string = environment.USER_REST_URL + '/login';
return this.httpClient.post<any>(url, credentials, options);

以及如何检索标题内容

this.userRestService.login(this.username, this.password).subscribe(
  response => {
    const token = response.headers.get('Authorization');
    this.authService.setJwtTokenToLocalStorage(token);
    this.router.navigate(['user']);
  },
  error => {
    console.log(error);
  }
);

0 个答案:

没有答案