在可观察的地图函数中正确声明Typescript类型

时间:2018-06-26 23:10:09

标签: angular typescript

我在Angular服务中具有此fetch函数。一切正常,但是TypeScript抱怨“类型'Object'上不存在属性'statuses'。”

我想我需要为数据对象创建一个接口,但是当我尝试这样做时,我不确定在哪里声明它。我也尝试声明HttpResponse,但这需要一个参数。任何线索都很好!

export class Status {
  constructor(
    public workflowId: string,
    public spawnTime: number,
    public spawnValue: string,
    public workflowName: string
  ) {
  }
}

fetch(command, params?) {
return this.http.post(`http://localhost:4000/${command}`, params)
  .pipe(
    map((data): Status[] => {
      const statuses = [];
      for (const status of Object.keys(data.statuses)) {
        const newStatus = new Status(
          status,
          data.statuses[status]['spawn-time'],
          data.statuses[status]['spawn-value'],
          data.statuses[status]['workflow-name']
        );
        statuses.push(newStatus);
      }
      return statuses;
    })
  )
  .pipe(
    catchError(this.handleError)
  );
}

2 个答案:

答案 0 :(得分:1)

好的,我在其他帖子的帮助下找到了答案。我必须为heroku restart创建一个接口,因为来自http请求的响应只是一个json对象。抱歉,我花了一段时间才意识到发生了什么事。这是不会出现TS错误或警告的整个工作解决方案:

data

答案 1 :(得分:0)

这是一个如何解析json中信息的示例。 在此示例中,您需要在{strong>第一个 map的内部map内部内部,它将作为迭代器工作,然后返回已解析的对象作为界面<Status>

 export interface Status {
       status1: string;
       status2: string;
       status3: string;
    }   


    fetch(command, params?) {
      return this.http.post(`http://localhost:4000/${command}`, params)
        .pipe(
           map((res: any) => {
              return res.map(res =>{
                   return <Status> {
                      status1: res.stausOne,
                      status2: res.stausTwo,
                      status3: res.stausThree,  
                   }
               });                   
           }))
        .pipe(
            catchError(this.handleError)
         );