简体   繁体   English

可观察到对象数组的映射

[英]Mapping Observable to array of objects

I have rest api which is returning me json array with data. 我有rest api,它会向我返回带有数据的json数组。 On client side I use this code to create objects from request. 在客户端,我使用此代码从请求创建对象。

public getNews(): Observable<News[]> {

return this.http.get(this.baseUrl + '/news')
  .pipe(
    catchError(this.handleError('getNews', []))
  )
  .map(res => {
    let response: any = res;
    return response.map((item) => new News(item));
  });
}

Subscribing: 订阅:

this.restProvider.getNews().subscribe((news: News[]) => {
  this.news = news;
});

But how can I resolve issue when response is not an array but only single element? 但是,当响应不是数组而是只有单个元素时,如何解决问题? Or response is wrong like for example unexpected data from API? 还是响应错误,例如来自API的意外数据?

Currently in those situations my application is throwing this error: 当前,在这些情况下,我的应用程序抛出此错误:

response.map is not a function response.map不是函数

The following peice of code should help you to handle errors: 以下代码片段应可帮助您处理错误:

this.restProvider.getNews().subscribe((news: News[]) => {
  this.news = news;
}, (err) => {
console.log(err);
});

You just need to add the error parameter in the subscribe function. 您只需要在subscription函数中添加error参数。

Now coming on to your first question : What if the response is a single object? 现在来回答第一个问题:如果响应是单个对象怎么办? -> The signature of the function will always force it to return an array. ->函数的签名将始终强制其返回数组。 The error will be generated on the subscription side. 该错误将在订阅端生成。 A simple solution to this is to change the data type of response. 一个简单的解决方案是更改响应的数据类型。

this.restProvider.getNews().subscribe((news:any) => {
  this.news = news;
});

Code, will always return array: 代码,将始终返回数组:

public getNews(): Observable<News[]> {

return this.http.get(this.baseUrl + '/news')
  .pipe(
    catchError(this.handleError('getNews', []))
  )
  .map(res => {
    if(Array.isArray(res)) {
       return res.map((item) => new News(item));
     } else {
       return [new News(res)];
     }
  });
}

When the response is either single object or an array, then it is obviously not consistent behavior and it complicates things. 当响应是单个对象或数组时,显然不是一致的行为,这会使事情变得复杂。 I assume that backend is not under your control. 我认为后端不受您的控制。

You can check first the response type to determine if it is an Array or an Object. 您可以先检查响应类型,以确定它是数组还是对象。 You can use Array.isArray() for it. 您可以使用Array.isArray() Then if the response is not an array, you convert it, like this const res = [response] 然后,如果响应不是数组,则将其转换,例如const res = [response]

From then on, the getNews() should always return an array 从那时起, getNews()应该始终返回一个数组

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

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