我有一个像这样填充的可观察对象:
this._mySubscription = this._myService.getSomething(id)
.subscribe(
response => this._myData = response,
error => this.displayError(<any>error),
() => this.stopLoading()
);
我可以像这样使用 Elvis 运算符在我的 HTML 标记中访问它的属性:
{{_myData?.PropertyNameHere}}
但是如何使用 TypeScript 访问组件中的相同属性?
这会在属性下产生一条波浪形的红线:
this._myData.PropertyNameHere
并说:
Property does not exist on Observable
更新: 服务调用示例
getSomething(id: string): Observable<any> {
let params = 'id=' + id;
return this._http
.post(apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.map((response: Response) => response.json().data.Items);
}
最佳答案
类中的
_myData
不应是 Observable
类型。它应该是您从服务中的 map
运算符返回的对象的类型。
.map((response: Response) => response.json().data.Items)
无论 data.Items
是什么类型,它都应该是 _myData
的类型。如果您不知道类型是什么,那么只需将其设为 any
。然后你可以在没有编译器警告的情况下用它做任何事情。但是如果你知道数据的结构,最好为它创建一个模型类,这样你就可以获得强类型
interface SomeModel {
somProperty: string;
}
getSomething(id: string): Observable<SomeModel> {
return this._http
...
.map((response: Response) => <SomeModel>)response.json().data.Items);
}
你的组件
class MyComponent {
private _myData: SomeModel;
this._mySubscription = this._myService.getSomething(id)
.subscribe((response: SomeModel) => this._myData = response,
error => this.displayError(<any>error),
() => this.stopLoading());
}
关于 Angular 2/ typescript : How to access observable property in component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022207/