如何从Angular Http响应中读取状态?

5

我在读取响应状态码时遇到了一些问题。

我正在调用服务中的API。

return this.http.get<string>( this.remoteServer + '/google.com/open', httpOptions);

在我的控制器中,我有以下代码:
open() {
    this.openService.open(this.selected.qrCode)
    .subscribe(
      data => {
       console.log(data);
       this.toastService.showSuccess('Unlock Successfull', 'success');
      }
    );
  }

现在我想要阅读http状态文本,

我从上面的调用中获得的示例http响应是:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://google.com/open", ok: false, …}

如何在控制器中读取状态文本。

请帮助我。


https://angular.io/guide/http#reading-the-full-response - JB Nizet
可能是如何在Angular 4中获取HttpClient状态码的重复问题。 - JB Nizet
4个回答

7
您可以在get请求中指定第二个参数为{ observe: 'response' },以获取完整的响应数据。
如果您想要发送其他选项,如headersparams,只需将它们全部捆绑在一个对象中。
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}), params : myParams, observe: 'response'}

Reference

return this.http.get<string>(
    this.remoteServer + '/google.com/open', httpOptions).subscribe((data) => {
        console.log(data.status);     // staus 200
        console.log(data.statusText);  // OK
});

什么是配置? - Anil
这是一个预期的响应类型。我只是使用了来自angular.io的代码。你可以在你的情况下将它作为字符串使用。 - Amit Chigadani
还有一个小问题,如果我想将http选项作为get()的第三个参数传递,它会显示只期望1-2个参数,但实际传入了3个。你能解释一下吗?感谢回复。 - Anil
你应该将它作为第二个参数发送,而不是与另一个属性{ observe: 'response', header : httpHeader}一起发送。我猜你想发送头信息。如果你想发送其他选项,只需将参数添加到第二个参数对象中即可。 - Amit Chigadani
不要混淆它与头文件,应该这样写:const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}), 'observe': 'response'} - Amit Chigadani
显示剩余3条评论

2
我们可以在请求中添加 { observe: 'response' } 来获取完整的响应。最初的回答。
return this._http.get<any>(this.serverUrl+'categories/'+id, { observe: 'response' })

1
{observe:'response'}选项限定符可以添加到HttpClient对象上的get或put中。它应作为附加逗号分隔字段添加到您可能已定义的任何现有选项中。请参见下面的示例,这是一个简单的Put语句,修改后返回完整的http内容。这可用于应用程序中的标准状态报告。
    body = this.currentDocument;

    let url = environment.base_url + 'api/Document/updateDocument';

    // For a put the options block is the third parameter. For a get this would be the second
    this.httpClient.put(url, body,
        {
            headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
            withCredentials: true,
            // Add the observe block to the existing option parameters
            observe:'response'
        })
        .subscribe(
            response => {

                statusMessage = new StatusMessage();
                statusMessage.HttpStatus = response.status;
                statusMessage.StatusText = response.statusText;

                // This example uses an EventEmitter but you could do any kind of logging here
                this.updateStatusPanel.emit(statusMessage);
                // The JSON body of this response can be accessed via the response.body parameter
            },
            err => {}
        );

0

data.status会给你想要的结果吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接