简体   繁体   English

Angular HttpModule如何处理从远程API接收的不适当的数据

[英]angular HttpModule how to handle inappropriate received data from a remote API

I am fetching data from remote API via Angular like this: 我正在像这样通过Angular从远程API获取数据:

this.http.get("https://example.com/getUsers").subscribe(users => {
  this.users = users.json();
});

And in HTML component: 在HTML组件中:

<ul>
  <li *ngFor="let x of users; let i = index">
    {{x.id}} {{x.body}}
  </li>
</ul>

Now when data is structured as it should be - array of json encoded documents, every thing is okay. 现在,当数据按应有的结构进行构造-JSON编码文档的数组时,一切都很好。

But if remote data structure will be changed from: 但是,如果远程数据结构将从以下位置更改:

[
 {
   // some object
 }
]

To

"just a string"

The app probably will be shut down due to two errors: 该应用可能会由于两个错误而被关闭:

  1. data received is not longer a valid json format. 收到的数据不再是有效的json格式。

  2. ngFor will be caused since its not an array. ngFor将由于不是数组而引起。

How to solve this? 如何解决呢?

In subscribe you are catching the onNext but you need to catch the onError too: 在订阅中,您正在捕获onNext,但您也需要捕获onError:

this.http.get("https://example.com/getUsers").subscribe(
  users => {
    this.users = users.json();
  },
  error => {
    console.log(error);
    this.users = [];
  }
);

Here you have more detail info about subscribe. 在这里,您可以了解有关订阅的更多详细信息。

By the way if your problem is, that the response is catched in the onNext and the problem is 'users' is not an array, you can check before: 顺便说一句,如果您的问题是在onNext中捕获了响应,而问题是“用户”不是数组,则可以在进行以下检查:

this.http.get("https://example.com/getUsers").subscribe(
  users => {
    // Check if users is an array, but you may check whatever you need.
    if (Array.isArray(users)) {
      this.users = users.json();
    } else {
      this.users = [];
    }
  },
  error => {
    console.log(error);
    this.users = [];
  }
);

There are two http headers that you need to know, first, there is a htpp request header called "Accept" , this header specify the mimetype that you will be accept, for example if you set the request header "Accept: application/json" before doing the http get, when the backend take the request and "did his job", it will be set a http response header called "Content-Type" , this header specify the mimetype of the response body. 您需要知道两个HTTP标头,首先是一个名为"Accept"的htpp请求标头,此标头指定您将接受的mimetype,例如,如果您将请求标头设置为"Accept: application/json"在执行http get之前,当后端接受请求并“完成工作”时,将设置一个名为"Content-Type"的http响应标头,该标头指定响应主体的模仿"Content-Type" If the "Accept" request header is not the same of "Content-Type" response header, it will be catched by OnError. 如果"Accept"请求标头与"Content-Type"响应标头不同,则OnError将捕获它。

Probably you are not specify the Accept header, so whatever the mimetype has the response body it will be catched by the onNext. 可能您未指定Accept标头,因此无论mimetype是否具有响应主体,onNext都会捕获它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM