angular - 如何在 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。那么我该如何映射呢???
解决方案
因为它的 TS - 没有运行时强制转换之类的东西。您只需键入提示 TS 编译器如何威胁给定对象。的情况下
this.getAutocompleteSuggestions().subscribe((data: MyTest)
您从字面上说:“接受订阅参数,并将其视为 MyTest,因此您将获得实际对象,因为它永远不会属于该类型(普通对象)。
如果您希望该实体具有精确类型,则必须自己对其进行转换(此处使用管道图)
推荐阅读
- amazon-web-services - AWS CodePipline (CI/CD) 用于更新现有 AWS Lambda 的代码(不是使用 CloudFormation 或 SAM 创建的)
- java - 如何让 hibernate-ogm 在 jboss eap 7.2 上工作?
- angular - Angular“解析 http://localhost:8000/excel 期间的 Http 失败”
- python - 为两个给定的百分位值拟合对数范数分布
- mongodb - 如何将所有数据从一个 Mongodb 云项目复制到另一个?
- vim - 如何在 VIM 中为自定义文件类型创建自定义配色方案
- ssl - 如何使letscrypt与cloudflare一起使用?
- python - Python 第二次如何更快地读取这个二进制文件?
- oracle - Oracle FOR ALL 更新不适用于随机分区(在 SAS 4gl 中)
- debugging - 退出 intellij 中的当前调试