Glenn Utter
Glenn Utter

Reputation: 2363

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

I have an observable that gets populated like this:

this._mySubscription = this._myService.getSomething(id)
                                .subscribe(
                                    response => this._myData = response, 
                                    error => this.displayError(<any>error),
                                    () => this.stopLoading()
                                );

I can access properties for it in my HTML markup using the Elvis operator like this:

{{_myData?.PropertyNameHere}}

But how do I access the same property in the component using TypeScript?

This produces a squiggly red line under the property:

this._myData.PropertyNameHere

And says:

Property does not exist on Observable

Update: Example of service call

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);

}

Upvotes: 4

Views: 9643

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208944

_myData in the class should not be of type Observable. It should be the type of the object that you are returning from the map operator in you service.

.map((response: Response) => response.json().data.Items)

Whatever type data.Items is, that should be the type of _myData. If you don't know what the type is, then just make it any. Then you can do whatever with it without compiler warnings. But if you know the structure of the data, it's best to create a model class for it so you get strong typing

interface SomeModel {
  somProperty: string;
}

getSomething(id: string): Observable<SomeModel> {

  return this._http
             ...
             .map((response: Response) => <SomeModel>)response.json().data.Items);
}

Your component

class MyComponent {
  private _myData: SomeModel;

  this._mySubscription = this._myService.getSomething(id)
    .subscribe((response: SomeModel) => this._myData = response, 
               error => this.displayError(<any>error),
               () => this.stopLoading());
}

Upvotes: 3

Related Questions