【问题标题】:How can I get Http response status code of my backend in Angular如何在 Angular 中获取后端的 Http 响应状态代码
【发布时间】:2021-08-07 21:29:56
【问题描述】:

我将 Angular 与 nodejs 一起用于后端,我想从后端服务器获取带有状态代码的响应。现在我只能获取响应数据,但我不知道如何获取状态码。我需要它来检查请求是如何进入后端服务器的。

这是我的 Angular CityService 代码...

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

export class CityService {

  constructor(private http: HttpClient) { }

  API_URI = 'http://localhost:5000'

  getCity(id: string) {
    return this.http.get(`${this.API_URI}/City/${id}`);
  }
}

如果我想从 Angular 项目的某个地方调用 getCity() 函数并获取它的状态码,我该怎么做?

感谢您的帮助!!! :)

【问题讨论】:

    标签: node.js angular http


    【解决方案1】:

    您可以通过将观察选项设置为“响应”来访问状态代码。这使您可以访问整个响应对象,而不仅仅是您的数据。这是一个例子,我认为它是不言自明的:

    export class CityService {
    
        private API_URI = 'http://localhost:5000';
    
        constructor(private http: HttpClient) { }
    
        public getCity(id: string): Observable<City> {
            return this.http.get<City>(
                `${this.API_URI/City/${id}}`,
                { observe: 'response' }
            );
        }
    }  
    

    然后在你的组件中,在你使用这个服务方法的地方,你可以订阅 observable 并读取如下状态码:

    export class CityComponent {
    
        constructor(private cityService: CityService) { }
    
        public requestCity(id: string): void {
            const city$ = this.cityService.getCity(id);
            
            city$.pipe(take(1)).subscribe(res => {
                console.log('status: ' + res.status);
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2021-03-15
      • 2021-01-28
      • 1970-01-01
      • 2014-10-17
      相关资源
      最近更新 更多