angularrxjsrxjs-observables

How to use Observable to emit each value from an array after every 1 second(Angular 5)?


I have a list of Products an array products:Product[]

Using Observable and Observer next method, I want to emit each product to my UI after every 1 second. How can I accomplish this?

This is what I tried , it is producing an infinite loop.Any help will be much appreciated.

 public streamAllProducts(): Observable<Product> {
    const products = this.ds.getProducts();

    const sequence = new Observable((observer) => {

      products.forEach(element => {


        setTimeout(() => {
          observer.next(element);
        }, 1000
        );
      });


    });
    return sequence;
  }

Solution

  • Here is a working example.

    The component that renders the desired effect will be doing the looping

    https://stackblitz.com/edit/angular-pzrfj1