解析打字稿中的JSON对象

时间:2019-02-03 15:43:55

标签: json typescript observable angular7

我对使用Spring Boot的Angular和建筑服务都是陌生的。因此,如果下面的问题很简单,请原谅。

我从spring rest服务获得以下JSON响应。我正在尝试将此服务响应映射到Angular材质数据表。

但是,当我仍然对Angular,Typescript和解析json对象还不熟悉时,能否请您提供有关如何将下面列出的json响应映射到我的界面的指针?

JSON响应

{
    "content": [
        {
            "id": "1000",
            "name": "R&D IN",
            "location": "IN",
            "costCenter": "RD-001"
        }
    ],
    "last": false,
    "totalElements": 10,
    "totalPages": 10,
    "size": 1,
    "number": 1,
    "sort": [
        {
            "direction": "ASC",
            "property": "name",
            "ignoreCase": false,
            "nullHandling": "NATIVE",
            "ascending": true,
            "descending": false
        }
    ],
    "first": false,
    "numberOfElements": 1
}

我需要在上面的json响应中映射以下两个属性-> 内容总记录

我在Angular中有以下服务代码

department.service.ts

getAllDepartments(filter: string, sortOrder: string, pageNumber: number, pageSize: number): Observable<DepartmentList>{

    return this.http.get<DepartmentList>(this.API_URL + '/api/department/', {
      params: new HttpParams()
          .set('filter', filter)
          .set('sort', 'name')
          .set('page', pageNumber.toString())
          .set('size', pageSize.toString())
    });
  }

department.component.ts

this.deptService.getAllDepartments(filter, sortDirection,pageIndex, pageSize)
      .pipe(
          catchError(() => of([])),
          finalize(() => this.loadingSubject.next(false)))
      .subscribe(
          departments => {
            let obj = JSON.stringify(departments);
            console.log('Department List :: ', departments);
            console.log(obj.content);
            this.departmentSubject.next(departments.content);
            this.departmentRecCount.next(departments.totalElements);
          });

但是,最后两行显示角度误差。但是,尽管有错误,该代码仍然可以工作

下面两行显示错误-

this.departmentSubject.next(departments.content);
this.departmentRecCount.next(departments.totalElements);

错误消息-错误TS2339:类型'any []中不存在属性'content'| DepartmentList”。属性“ content”在类型“ any []”上不存在。

Department.model.ts

export interface DepartmentList {
    content: Department[];
    totalElements: number;
  }

  export interface Department {
    id: string;
    name: string;
    location: string;
    costCenter: string;
  }

如何解决上述问题。

如果已经在其他任何话题中对此进行了解释,请原谅。

1 个答案:

答案 0 :(得分:1)

在分配强制类型departments之前尝试输入。

const deptList = departments as DepartmentList;

this.departmentSubject.next(deptList.content);
this.departmentRecCount.next(deptList.totalElements);