I dont get rxjs 6 with angular 6 with interval, switchMap, and map

前端 未结 2 1383
失恋的感觉
失恋的感觉 2020-12-30 01:03

I want to update my rxjs code to 6 got I don\'t get it.

Before I had the below that wouth poll for new data every 5 seconds:

import { Observable, int         


        
相关标签:
2条回答
  • 2020-12-30 01:20

    The code should be something like the following. You need to use the pipe operator.

    import { interval } from 'rxjs';
    import { switchMap, map } from 'rxjs/operators';
    
    const result = interval(5000).pipe(
    switchMap(() => this._authHttp.get(url)),    
    map(res => res.results)
    )
    
    0 讨论(0)
  • 2020-12-30 01:23

    After lot of research I could came up with the following updated approach from RxJs' 6 with Angular 6.

    The search API is called after each interval of 5 sec and unsubscribed once the count > 5 :

    let inter=interval(5000)
    
    let model : ModelComponent;
    model=new ModelComponent();
    model.emailAddress="mdshahabaz.khan@gmail.com";
    
    
    let count=1;
    this.subscriber=inter.pipe(
              startWith(0),
              switchMap(()=>this.asyncService.makeRequest('search',model))
            ).subscribe(response => {
              console.log("polling")
              console.log(response.list)
              count+=1;
              if(count > 5){
                this.subscriber.unsubscribe();
              }
            });
    

    API request :

       makeRequest(method, body) : Observable<any> {
        const url = this.baseurl + "/" + method;
    
        const headers = new Headers();
        this.token="Bearer"+" "+localStorage.getItem('token'); 
        headers.append('Authorization', this.token);
        headers.append('Content-Type','application/json');
    
        const options = new RequestOptions({headers: headers});
        return this.http.post(url, body, options).pipe(
            map((response : Response) => {
                var json = response.json();                
    
               return json; 
            })
        );
    }
    

    Dont forget to unsubscribe to avoid memory leak.

    ngOnDestroy(): void {
    if(this.subscriber){
      this.subscriber.unsubscribe();
    }
    

    }

    0 讨论(0)
提交回复
热议问题