简体   繁体   中英

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

I am fetching data from remote API via Angular like this:

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

And in HTML component:

<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.

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.

  2. ngFor will be caused since its not an array.

How to solve this?

In subscribe you are catching the onNext but you need to catch the onError too:

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:

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. If the "Accept" request header is not the same of "Content-Type" response header, it will be catched by OnError.

Probably you are not specify the Accept header, so whatever the mimetype has the response body it will be catched by the onNext.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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