繁体   English   中英

Angular 2 / TypeScript:如何访问组件中的可观察属性

[英]Angular 2 / TypeScript: How to access observable property in component

我有一个像这样填充的 observable:

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

并说:

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中的_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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM