首页 > 解决方案 > 如何在 Angular 5 中以自定义类型映射 API 响应

问题描述

我有这个接口来塑造我的 API 响应 -

 interface MyTest {
 property2: string
 }

这是我的 Angular 5 服务代码 -

getAPI(searchKey: string) {
this.productsAPIUrl = 
                  https://localhost:44331/api/SampleData/WeatherForecasts2";

return this.http.get<MyTest>(this.productsAPIUrl);
}

我的实际 API 响应 - https://localhost:44331/api/SampleData/WeatherForecasts2

{"property1":"Property1","property2":"Property2","property3":"Property3"}

现在我在我的组件中调用这个 Angular 服务,如下所示 -

public incrementCounter() {

this.getAutocompleteSuggestions().subscribe((data: MyTest) => {
  console.log(data);
});
}

所以这里我的问题是在调用 Angular 服务之后,我得到了完整的响应。但是在这里,我将我的 API 响应转换为只有 property2 的“MyTest”类型,但为什么我会得到完整的响应?

如何在子集中投射我的 API 响应?如何提取 API 响应以及如何将其映射到我的自定义模型类型 MyTest????

我只需要Property2。那么我该如何映射呢???

标签: angulartypescriptangular5angular6typescript2.0

解决方案


因为它的 TS - 没有运行时强制转换之类的东西。您只需键入提示 TS 编译器如何威胁给定对象。的情况下

this.getAutocompleteSuggestions().subscribe((data: MyTest)

您从字面上说:“接受订阅参数,并将其视为 MyTest,因此您将获得实际对象,因为它永远不会属于该类型(普通对象)。

如果您希望该实体具有精确类型,则必须自己对其进行转换(此处使用管道图)


推荐阅读