error while trying to get the observable data in UI

Viewed 83

I have an observable that simply gives the double of values from 1 to 5:

obs = new Observable(observer => {
        console.log('Observable starts')
        observer.next(1);
        observer.next(2);
        observer.next(3);
        observer.next(4);
        observer.next(5);
        observer.complete();
    }).pipe(
        tap(data => console.log('tap ' + data)), 
        map((val) => { return val as number * 2 }),
        tap(data => console.log('final ' + data)),
    )

To get the values in UI, I wrote the following line of code:

this.obs.subscribe({ next: val => { this.var1 = val } })

Now, when I am trying to retrieve these values in UI using NgFor, *ngFor="let v1 of var1" UI code

I am getting the error as: Type 'number' is not assignable to type 'NgIterable | null | undefined'.

How can I get the values to show up in UI? Where am I going wrong with my above code?

1 Answers

You are setting this.var1 to each number emitted by the observable, then trying to use it as an array.

If you want to set var1 as an array then you should either....

  1. Pipe toArray() So that rather than emit each number, it waits until the upstream completes and then emits one array. Or,

  2. Initialize var1 as an empty array, and change your subscription line to this.obs.subscribe({ next: var => this.var1.push(var) })

Related