Search code examples
arraysangulartypescriptobservable

is it possible to use push() to add element into observable array


I created an Observable array of type string. like below

products: Observable<string[]>;

I want to push some elements into products array. I don't want to use subscribe methods here. it is not allowing me to use the normal push method. see below code

this.products.push("mova");

what is the alternative for the above code(push element to an array)? tell me one simple way to do it. Please don't use any dependency injection here to perform the next() and subscribe().


Solution

  • You can't push to the property which is an Observable of string[] because it is expected that it will have a stream of data which will set the values in future.

    What you can do is:

    products: Observable<string[]>;
    items: string[] = [];
    
    // push the values in it.
    
    this.products = of(items); // <--it will set the observables of string[]
    

    Still you need to subscribe to the products observables to get the data.