Angular 2/ typescript : How to access observable property in component

标签 angular typescript 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

并说:

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/

相关文章:

javascript - Express Subscribe 调用中的 JSON 数组出现 Angular HTML 绑定(bind)错误

angular - 订阅可观察的输入

javascript - 在 Angular 4 中单击时滚动到元素

javascript - 使用 Observable 在控制台中打印数据 - Angular 2

angular - 没有请求返回值时RxJS超时不报错

Angular 6 - rxjs 管道不适用于 valueChanges

javascript - Angular 6 服务无法通过单元测试(NullInjectorError : No provider for HttpClient!)

Angular 5 Material 5 MatTableDataSource.. ."' mat-card-title' 不是已知元素。”

javascript - 从结构指令向父组件发射事件不起作用

javascript - 使用 TypeScript 在 Knockout JS 中正确注释对象数组