簡體   English   中英

Angular 6/7 - 獲取整個http響應狀態

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

我在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(...),我會收到訂閱不是函數的錯誤。

另外,我只在管道中獲得200個狀態響應(map())。 我在這里沒有得到其他狀態代碼的回復。

我想根據收到的狀態更新BehaviorSubject。

如何獲得服務中的所有回復及其狀態?

我已經走了Angular 6獲取帶有httpclient問題的響應標頭 ,但這不適用於此處。

我添加了觀察:對http標頭的'響應',但它沒有任何區別。

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

我就是這樣做的:

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

使用Angular HttpClient並訂閱從http.get返回的http.get

所以你可以做到這一點

我的方法允許您在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)); 

在Angular 7中,使用攔截器向請求添加標頭的最佳方法是。 在攔截器中,您可以向請求添加標頭,因此,您可以訪問受保護的API。 這是攔截器示例,它為請求添加標頭:

       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)

使用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;
 }));

現在, HttpClient.get()返回一個類型為HttpResponse的Observable,而不僅僅是JSON數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM