Node.js 如何在Angular中获取后端的Http响应状态代码
我使用angular with nodejs作为后端,我希望从后端服务器获得状态代码的响应。目前,我只能获得响应数据,但我不知道如何获得状态代码。我需要它来检查请求是如何进入后端服务器的 这是我的城市服务代码Node.js 如何在Angular中获取后端的Http响应状态代码,node.js,angular,http,Node.js,Angular,Http,我使用angular with nodejs作为后端,我希望从后端服务器获得状态代码的响应。目前,我只能获得响应数据,但我不知道如何获得状态代码。我需要它来检查请求是如何进入后端服务器的 这是我的城市服务代码 import { HttpClient } from '@angular/common/http'; export class CityService { constructor(private http: HttpClient) { } API_URI = 'http://
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()函数并获取其状态代码,我该怎么做
谢谢你的帮助!!!:) 您可以通过将“观察”选项设置为“响应”来访问状态代码。这使您能够访问整个响应对象,而不仅仅是数据。下面是一个例子,我认为这是自我解释:
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' }
);
}
}
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);
});
}
}