typescript 将 Observable 映射到对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49792196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:21:19  来源:igfitidea点击:

Mapping Observable to array of objects

angulartypescriptionic-framework

提问by jankes83

I have rest api which is returning me json array with data. On client side I use this code to create objects from request.

我有rest api,它返回带有数据的json数组。在客户端,我使用此代码从请求创建对象。

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 不是函数

回答by Prasheel

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.

您只需要在订阅函数中添加错误参数即可。

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;
});

回答by Yerkon

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)];
     }
  });
}

回答by David Votrubec

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. Then if the response is not an array, you convert it, like this const res = [response]

您可以先检查响应类型以确定它是数组还是对象。你可以用Array.isArray()它。然后如果响应不是数组,你就转换它,像这样const res = [response]

From then on, the getNews()should always return an array

从那时起,getNews()应该总是返回一个数组