简体   繁体   English

如何将对象数组映射到我的类型数组

[英]How to map object array to my type array

I have a class: 我有一堂课:

export class    Stuff {
      id: string;
      namd: string;
    }

With angular < 4.3 I have this call: 使用angular < 4.3我有这个电话:

getStuff(): Observable<Stuff[]> {
    return this.http.get('api-url-here/stuff')
        .map((data: Response) => {
            return data.json()
                .map((item: any) => {
                    return {
                    id: item.id,
                    name: item.name
                };
        });
    })
}

With angular >= 4.3 I changed it to this: 使用angular >= 4.3我将其更改为:

getStuff(): Observable<Stuff[]> {
    return this.http.get<Stuff[]>('api-url-here/stuff')
        .map((data: any) => {
            return data
                .map((item: any) => {
                    return {
                    id: item.id,
                    name: item.name
                };
        });
    })
}

I am receiving the array of stuff fro my api that looking like that. 我正在从我的api收到一系列类似的东西。

[
 {"id":1,"name": "name" }
]

As you can see from the code example above I have to map the data twice to get my type shape ( Stuff[] ). 从上面的代码示例中可以看到,我必须将数据map两次以得到我的类型形状( Stuff[] )。 Is there a better way of doing this with angular 4.3+ ? 有没有更好的方法来做到这一点与angular 4.3+

You are using typed response in new HttpClientModule , so in first map your result is already parsed. 您正在新的HttpClientModule中使用类型化的响应,因此在第一个map您的结果已被解析。

getStuff(): Observable<Stuff[]> {
  return this.http.get<Stuff[]>('api-url-here/stuff');
}

Should work. 应该管用。 And then 接着

SomeStaffService.getStuff().subscribe(staff => console.log(staff));

Update: 更新:

In this case you will be able to handle the errors in two ways. 在这种情况下,您将能够以两种方式处理错误。 Outside of your service 在您的服务之外

SomeStaffService.getStuff().subscribe(
  staff => console.log(staff),
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      console.log("Client-side error occured.");
    } else {
      console.log("Server-side error occured.");
    }
  }
);

Or you can subscribe right in your service and catch the error there. 或者,您可以直接在您的服务中订阅并在其中捕获错误。 Please refer to documentation 请参考文档

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

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