首页 > 解决方案 > Angular 7 HttpClient 响应类型作为类

问题描述

我正在尝试使用 httpclient 从 http get 调用中转换我的响应并创建我创建的类的实例。

问题
HttpClient 似乎没有使用其响应对象的属性创建我的类的新实例。请帮忙!

我尝试过创建一个类与接口。不知道我还需要在这里做什么。

我的课

export class Escalation {    
  constructor(private NAME: string, private DESCRIPTION: string) { }    

  public get name() {    
    return this.NAME;    
  }

  public set name(name: string) {    
    this.NAME = name;    
  }

  public get description() {    
    return this.DESCRIPTION;    
  }

  public set description(description: string) {    
    this.DESCRIPTION = description;    
  }    
}

我的服务

public getEscalation(escalationName) {    
    return this.http.get(`${this.globals.baseRestUrl}/companies/escalations/${escalationName}`);    
  }

我的组件

public escalation: Escalation = new Escalation('', '');    

this.companiesService.getEscalation(escalationName).subscribe(    
        (escalationResponse: Escalation) => this.escalation = {    
          ...escalationResponse    
        }, (error: any) => {       
          console.log(error);   
        }    
      );

预期结果
我希望我的响应在 api 回调时被强制转换为类型 Escalation (My class)。


api 的 实际结果返回一个对象,如下所示:

{    
    NAME: 'Escalation 1',    
    DESCRIPTION: 'This is a test description'    
}   

但最终 this.escalation 返回 undefined

我希望我解释得很好。如果您需要更多信息,请告诉我!

标签: httpclientgetter-setterangular7typechecking

解决方案


(escalationResponse: Escalation)行代码并不是真的要转换来自HttpClient 的响应,而是要推断它是什么类型。

您可以考虑将代码调整为this.escalation = new Escalation(escalationResponse.NAME, escalationResponse.DESCRIPTION)

我相信this.escalation = { ...escalationResponse }无论如何只是解构属性。


推荐阅读