Angular-如何将httpClient.request()收到的对象映射到Angular中的接口

时间:2020-02-12 14:23:14

标签: angular

我在后端部分的方法中有一个对象,我用httpClient.request()调用

this.httpClient.request<YearlyOverview[]>('get', `${this.configService.get('serverMethodsUrl')}api/ServerMethods/getPresencesByEmployeeIdAndYear`, {
    withCredentials: true,
    params: new HttpParams().set('userId', '292')
                            .set('year', '2019')
  }).subscribe((result: any) => {
            myArray = result;
  });

返回的对象看起来像这样:

myArray: 
  [
    {
    id: 1,
    name: "Mike",
    presences: [
                    {
                        month: 1,
                        current: 50,
                        total: 170,
                        days: [
                                {day: 1, total: 8.5},
                                {day: 2, total: 8.5},
                                {day: 3, total: 8.5},
                                {day: 4, total: 8.5},
                                .............
                            ]
                    }
                ]
    }
  ] 

因此,基本上,有3个嵌套数组。

只是给您一个想法,它显示了所选雇员每天的所有工作时间。

与此同时,我的接口略有不同,最大的区别是第三个数组不存在,它在"days"中包含了"presences"数组:

export interface YearlyOverview {
  id: number;
  name: string;
  presences: Array<YearlyPresence>;
}

export interface YearlyPresence {
  month: number;
  current: number;
  total: number;
  day1: number;
  day2: number;
  day3: number;
  day4: number;
  day5: number;
  day6: number;
  day7: number;
  ...and so on up to day31
}

现在,我正在尝试将我从HttpClient收到的对象映射到我的Interface,但是我需要一些帮助。谁能指出我正确的方向?

我想映射到我的界面的“ day1”,即当天的“ total”的值。

谢谢

1 个答案:

答案 0 :(得分:0)

我没有测试,但是类似的东西

this.httpClient.request<YearlyOverview[]>('get', `${this.configService.get('serverMethodsUrl')}api/ServerMethods/getPresencesByEmployeeIdAndYear`, {
    withCredentials: true,
    params: new HttpParams().set('userId', '292')
        .set('year', '2019')
}).pipe(
    map(values => values.map(year => {
        year.presences = year.presences.map(presence => {
            presence.days.forEach(day => presence['day' + day.day] = day.total)
        })
    }))
    )
    .subscribe((result: YearlyOverview[]) => {
        myArray = result;
    });