【问题标题】:Angular 7 HttpClient response type as classAngular 7 HttpClient 响应类型作为类
【发布时间】:2019-01-03 00:32:08
【问题描述】:

我正在尝试使用 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

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

【问题讨论】:

  • this.companiesService.getEscalation(...) 什么时候被调用?
  • 这在我的自定义组件的 Oninit 方法@Mitch Wilkins 中调用
  • 所以当您将 this.escalation 记录到控制台时,您会得到未定义但 API 返回所需的结果?
  • API 返回 json 响应,但我想将其转换为我的自定义 Escalation 类,如果这有意义的话,这不会发生。 @米奇威尔金斯

标签: httpclient getter-setter angular7 typechecking


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2023-01-18
    • 2019-06-20
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2019-05-18
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多