Home > Software engineering >  While implementing ngrx Observable is showing Object of unknown type
While implementing ngrx Observable is showing Object of unknown type

Time:11-30

This is my component's typescript code:

import { Component, Input, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-counter-output',
    templateUrl: './counter-output.component.html',
    styleUrls: ['./counter-output.component.css']
})
export class CounterOutputComponent implements OnInit {
    counter!: number;
    counter$!: any;

    constructor(private store: Store<{ counter: { counter: number } }>) {
    }

    ngOnInit(): void {

        this.store.select('counter').subscribe((data) => {
            this.counter = data.counter;
            console.log(data);
        });
        this.counter$ = this.store.select('counter');
        console.log(this.counter$);
    }
}

This is its HTML template:

<div>This is the counter:{{(counter$|async).counter}}</div>
<div>This is the counter:{{counter}}</div>

There is an error in line no 1 in the HTML file.

enter image description here

When I am subscribing in the typescript file I am able to get the value, but when I am using it as an observable it is showing an error.

CodePudding user response:

Set a type to counter$.

export interface Counter {
    counter: number;
}

....

counter$: Observable<Counter>;

Of course, you have to be sure that the selector returns Counter as data.

EDIT: If you insist to use any (which beats the purpose of using Typescript), you can use the $any() type cast function to suppress this error.

<div>This is the counter:{{ ($any(counter$|async)).counter }}</div>

CodePudding user response:

Have you tried to actually define your counter$ property as an Observable?

Why declare it as any if you already know what type of data is?

export interface myInterfaceData {
   counter: number;
}
counter$!: Observable<myInterfaceData>;
<ng-container *ngIf="{ myCounter: counter$ | async } as observable">
  <div>
    This is the counter: {{ observable.myCounter?.counter }}
  </div>
</ng-container>
  • Related