Angular 6/7-获取服务中的整个http响应状态

时间:2019-05-21 03:50:04

标签: angular angular-httpclient

我在Angular 7中提供以下服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class UserService {

  private currentUserSubject: BehaviorSubject<any>;

  constructor(
    private http: HttpClient
  ) {
    this.currentUserSubject = new BehaviorSubject(null);
  }

  public get currentUserValue(): any {
    return this.currentUserSubject.value;
  }

  login(entity: any, inputUsername: any, inputPassword: any): any {

    const httpOptions = {
      headers: new HttpHeaders({
        username: inputUsername,
        password: inputPassword
      })
    };

    return this.http.get(entity.url, httpOptions)
    .pipe(map((user: Response) => {
      console.log(user);
      console.log(user.status);

      if (user) {
          this.currentUserSubject.next(user);
      }
      return user;
  }));
  }
}

我想获取响应状态(200、401等)。如果我尝试订阅.pipe(map(。(....))。subscribe(...),则会出现错误,表明subscribe不是函数。

此外,我在pipe(map())中仅获得200个状态响应。我在这里没有收到其他状态代码的回复。

我想根据收到的状态更新BehaviorSubject。

如何获取服务中的所有回复及其状态?

我已经通过Angular 6 Get response headers with httpclient issue,但这在这里不适用。

我添加了观察:对HTTP标头的“响应”,但没有任何区别。

const httpOptions = {
      headers: new HttpHeaders({
        username: inputUsername,
        password: inputPassword,
        observe: 'response',
      }),
    };

4 个答案:

答案 0 :(得分:0)

这就是我的做法:

this.http.get(this.url, { observe: 'response' })
  .subscribe(response => console.log(response.status));

使用Angular HttpClient并订阅http.get返回的可观察对象。

答案 1 :(得分:0)

所以你可以这样做

我的方法允许您在API中添加所需的响应类型


import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token',
    'observe': 'response' 
  })
};

this.http.get(this.url, httpOptions).subscribe(response => console.log(response.status)); 

答案 2 :(得分:0)

在Angular 7中,向请求添加标头的最佳方法是使用拦截器。在拦截器中,您可以将标头添加到请求中,从而可以访问受保护的API。这是将标头添加到请求的拦截器示例:

irkernel

答案 3 :(得分:0)

通过观察选项告诉HttpClient您想要完整的响应:

const httpOptions:any = {
  headers: new HttpHeaders({
    username: inputUsername,
    password: inputPassword
  }),
  observe: 'response',
};
return this.http.get<any>(entity.url, httpOptions) //I put the type of the response data as `any` you can put the type of user
 .pipe(map((user: HttpResponse<any>) => {//same type as above statement
   console.log(user);
   console.log(user.status);

   if (user) {
      this.currentUserSubject.next(user);
   }
   return user;
 }));

现在,HttpClient.get()不仅返回JSON数据,还返回类型为HttpResponse的Observable。