Angular 4 / Express中的访问响应状态代码

时间:2017-10-31 12:14:17

标签: angular rest http express

我正在向Express REST API发出GET请求,并在将res.status设置为200后返回数据。在Angular中,响应包含数据,但response.status始终未定义。

[编辑开始]

根据MartinAdámek在下面的回答,我尝试更改我的get请求以使用Observable而不是Promise,并在请求中包含{ observe: 'response' }。但回应完全相同 - 仍然没有回应。状态。

Angular 4 get(with Observable)

requestNew(endPoint:string, type:string, query:string, data:any) {
  this.http[type](this.configService.apiHost + endPoint + query, data ? data : '', { observe: 'response' })
    .subscribe(
      (response:HttpResponse<any>) => {
        console.log(response) // Array containing expected data
        console.log(response.status) // undefined
      }
    )
}

[编辑结束]

Angular 4 get

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

request(endPoint:string, type:string, query:string, data:any) {
  let promise = new Promise((resolve, reject) => {
    this.http[type](this.configService.apiHost + endPoint + query, data ? data : '')
      .toPromise()
      .then((response: HttpResponse<any>) => {
        resolve(response);
      })
      .catch((error: HttpErrorResponse) => {
      })
  });
  return promise;
}

Express API:

router.get('/clients', (req, res) => {
  clientService.GetClients()
    .then((data) => {
      res.status(204).json(data); // data is sent
    })
})

如何在Angular 4中访问response.status?

1 个答案:

答案 0 :(得分:2)

HttpClient会自动从JSON转换有效负载并将其传递给您。如果要访问整个响应对象,可以执行以下操作:

http
  .get('/data.json', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.status);
  });

https://angular.io/guide/http#reading-the-full-response

https://angular.io/api/common/http/HttpResponse

另请注意,GETDELETE方法的签名与POSTPUT不同,没有有效内容参数,因此您需要将{observe: 'response'}传递为这些方法的第二个参数。