Json 从对专用对象的映射和管道HTTP响应中访问特定属性
我不熟悉Angular和TypeScript,但我正在尝试编写应用程序,它将根据从REST服务检索到的响应进行一些操作 我决定使用,以便从RESTAPI生成服务和模型。模型被创建为接口,虚拟响应。ts:Json 从对专用对象的映射和管道HTTP响应中访问特定属性,json,angular,typescript,Json,Angular,Typescript,我不熟悉Angular和TypeScript,但我正在尝试编写应用程序,它将根据从REST服务检索到的响应进行一些操作 我决定使用,以便从RESTAPI生成服务和模型。模型被创建为接口,虚拟响应。ts: export interface DummyResponse { name?: string; order?: number; } 服务虚拟服务。ts有两种方法: getDummyResponse(): __Observable<__StrictHttpResponse&l
export interface DummyResponse {
name?: string;
order?: number;
}
服务虚拟服务。ts有两种方法:
getDummyResponse(): __Observable<__StrictHttpResponse<DummyResponse>> {
// some code with headers, params etc...
return this.http.request<any>(req).pipe(
__filter(_r => _r instanceof HttpResponse),
__map((_r) => {
return _r as __StrictHttpResponse<DummyResponse>;
})
);
}
getDummy(): __Observable<DummyResponse> {
return this.getDummyResponse().pipe(
__map(_r => _r.body as DummyResponse)
);
}
如何正确地将此数据映射到DummyResponse对象并访问其中一个字段?即使最后一个控制台打印了正确的值,Angular也会抛出一个关于DummyResponse类型上不存在属性的错误(这是正确的)。但我不明白为什么数据不是真正的DummyResponse,甚至VisualStudio代码都说数据是DummyResponse的类型
我错过了什么?有人能告诉我发生了什么事吗?vs code相信你说的“嘿……我知道即将到来的数据是
DummyResponse
”类型。没有运行时检查。啊,我明白了,但是如何在那里检索我需要的东西?@AJT82但为什么数据不是DummyResponse的类型?为什么我不能访问它的字段?看来你的回复有一个dummyResponse
对象和你想要的数据,所以你需要做:\u r.body.dummyResponse as dummyResponse
@AJT82我同意你的看法,但正如我在帖子中提到的,编译后,我在终端中看到错误,即类型dummyResponse
上不存在属性dummyResponse
。因此,从一个方面来说,它是正确的,其他形式的not.vs代码信任您,当您说“嘿……我知道即将到来的数据是DummyResponse
”类型时。没有运行时检查。啊,我明白了,但是如何在那里检索我需要的东西?@AJT82但为什么数据不是DummyResponse的类型?为什么我不能访问它的字段?看来你的回复有一个dummyResponse
对象和你想要的数据,所以你需要做:\u r.body.dummyResponse as dummyResponse
@AJT82我同意你的看法,但正如我在帖子中提到的,编译后,我在终端中看到错误,即类型dummyResponse
上不存在属性dummyResponse
。因此,从一个方面来说,它是正确的,从另一个方面来说,它不是。
private resp: DummyResponse;
constructor(private dummyService: DummyService) {}
getName() {
this.dummyService.getDummy().subscribe(data => {
let json = JSON.stringify(data);
this.resp = data;
console.log(json); // {"dummyResponse":{"name":"default","order":1}}
console.log(this.resp); // {dummyResponse: {…}}
// > dummyResponse: {name: "default", order: 1}
// > __proto__: Object
console.log(this.resp.name); // undefined
console.log(this.resp.dummyResponse.name); // default
});
}