简体   繁体   English

Angular 6/7 - 获取整个http响应状态

[英]Angular 6/7 - get entire http response status in service

I have following service in Angular 7: 我在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;
  }));
  }
}

I want to get the response status (200, 401, etc.). 我想获得响应状态(200,401等)。 If I try to subscribe such as .pipe(map(.....)).subscribe(...), I get error that subscribe is not a function. 如果我尝试订阅如.pipe(map(.....))。subscribe(...),我会收到订阅不是函数的错误。

Also, I get only the 200 status responses in pipe(map()). 另外,我只在管道中获得200个状态响应(map())。 I do not get responses with other status codes here. 我在这里没有得到其他状态代码的回复。

I want to update the BehaviorSubject based on the received status. 我想根据收到的状态更新BehaviorSubject。

How can I get all the responses and their status in the service? 如何获得服务中的所有回复及其状态?

I have gone though Angular 6 Get response headers with httpclient issue , but that does not apply here. 我已经走了Angular 6获取带有httpclient问题的响应标头 ,但这不适用于此处。

I added observe: 'response' to http headers, but it did not make any difference. 我添加了观察:对http标头的'响应',但它没有任何区别。

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

This is how I did it : 我就是这样做的:

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

Using Angular HttpClient and subscribing to the observable returned from http.get . 使用Angular HttpClient并订阅从http.get返回的http.get

So you can do this 所以你可以做到这一点

My approach let you append response type you want in your API 我的方法允许您在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)); 

in Angular 7, the best way to add header to the request is, using the interceptor. 在Angular 7中,使用拦截器向请求添加标头的最佳方法是。 in the interceptors, you can add header to the request and as a result, you can access to the protected API. 在拦截器中,您可以向请求添加标头,因此,您可以访问受保护的API。 here is the interceptor sample which adds header to the request : 这是拦截器示例,它为请求添加标头:

       intercept(request: HttpRequest<any>, next: HttpHandler): 
            Observable<HttpEvent<any>> {
            let currentUser = this.authservice.currentUser;
         if (currentUser && currentUser.token) {
           request = request.clone({
           setHeaders: {
           Authorization: `Bearer ${currentUser.token}`
           }
          });
         }

         return next.handle(request)

Tell HttpClient that you want the full response with the observe option: 使用observe选项告诉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;
 }));

Now HttpClient.get() returns an Observable of typed HttpResponse not just the JSON data. 现在, HttpClient.get()返回一个类型为HttpResponse的Observable,而不仅仅是JSON数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM