Mohamed Sahir
Mohamed Sahir

Reputation: 2543

How to call a service call in each 2 minutes in angular4 observable

In service

this._ProductUrl =".../api/products"

getProduct(): Observable <IProduct[]>{   
  return this._http.get(this._ProductUrl)
    .map((response:Response) =>  <IProduct[]> response.json())
    .catch(this.handleError);
}  

app.component.ts

with interval not working

Observable
  .interval(2*60*1000)
  .timeInterval()
  .flatMap((this._productService.getProduct())
  .subscribe((response) => {

}),(err)=> {this.errorMsg =<any>err};

while hover over the line some error displays. Error in this line:

    Argument of type '(err: TimeInterval<number>) => void' is not assignable to parameter of type '(value: TimeInterval<number>, index: number) => ObservableInput<{}>'.

  Type 'void' is not assignable to type 'ObservableInput<{}>'

when tried like this

  Observable
    .interval(2*60*1000)
    .timeInterval()
    .flatMap((this._productService.getProduct(response))).subscribe((response) => {

    }),(err)=> {this.errorMsg =<any>err};

Error on this line:

.flatMap((this._productService.getProduct(response)

 [ts] Expected 0 arguments, but got 1.
(property) AppComponent._productService: ProductServic

e

without Interval working fine

 this._productService.getProduct().subscribe((response) => {
console.log(error);

}),(err)=> {this.errorMsg =<any>err};

There is some syntax issue with above codes, please provide better solution be appreciated

Upvotes: 0

Views: 118

Answers (2)

Chandru
Chandru

Reputation: 11184

try like this :

Observable.interval(2000).subscribe((x) => {
    this._productService.getProduct()
        .subscribe((response) => {
            console.log('response', response)
        })
})

OR using flatMap() you can try like this below

Observable.interval(2000)
    .timeInterval()
    .flatMap((x) => {
        return this._productService.getProduct()
    })
    .subscribe((response) => {
        console.log('response', response);
    })

Upvotes: 4

Eugen Tatuev
Eugen Tatuev

Reputation: 75

Give a try with a bit changed error handling and single subscribe:

      Observable
        .interval(2000)
        .switchMap(() => {
            return this._productService.getProduct();
        })
        .catch(err => {
            // handle errors
            this.errorMsg = <any>err;
            // rethrow error
            return Observable.throw(err);
            // or just return some correct value
            // return Observable.of(new Product())

        })
        .subscribe(response => console.dir(response));

UPD: mistake at response logging

Upvotes: 0

Related Questions