Home > Software engineering >  Child nodes of an Observable not being recognised
Child nodes of an Observable not being recognised

Time:06-25

I have the following data object interface:

interface MainGameObject {
        credits: Credit[];
        localisation: Localisation;
    }

(Am I of course declaring the types for credits and localisation too).

In my component I declare my gameData$ object as an observable as I wish to use this with the async pipe in my template.

gameData$ = of({}) as Observable<MainGameObject>;

ngOnInit() {
        this.gameData$ = this.generalService.getAllGameData();
    }

And so far this works fine. However if I wish to get the child nodes of either 'credits' or 'localisation' elsewhere in my file such as:

getCredits()
{
console.log(this.gameData$.credits);
}

My VS code says the following error:

Property 'credits' does not exist on type 'Observable<MainGameObject>'

Why? MainGameObject imports my root object and 'credits' or 'localisation' have been specifically declared.

I can list out things on the template side ie: *ngFor="let credit of (gameData$ | async)?.credits" but I can't access it in the typescript file.

CodePudding user response:

gameData$ is an Observable, which does not have credits property, as the error message says so. You are using this Observable in the template with the async pipe, which allows you to subscribe to it, and access the values it emits, but only in the template. If you want to use it in your component class file as well, you will need to manually subscribe to it.

You can add another property to the class, and assign it the value like this:

ngOnInit() {
    this.gameData$ = this.generalService.getAllGameData();
    this.gameData$.subscribe(data => {
      this.gameData = data;
    })
}

However, the drawback of this approach is that you have to manually unsubscribe to this Observable. This is not the case with the async pipe in the template, which automatically subscribes and then eventually unsubscribes when the component is destroyed. Not doing so will create a memory leak in your application.

  • Related