更新订阅中的值

时间:2019-01-15 08:21:25

标签: rxjs angular7 rxjs6

我有一个服务定期api调用,如果这是第一次调用,它将更改url。

它具有用于生成api调用的时间间隔订阅,我不能使用全局变量,因为它是一项无需删除注入器即可被调用的服务。

getData(init: boolean): Observable<any> {

   const refreshInterval = 5000;
   const interval = observableInterval(refreshInterval).pipe(startWith(0)) 

  return interval.pipe(
    flatMap(() => this.http.get<any>(this.getUrl(init))), 
    map((data) => this.doWhateverWithData(data)),
  );

}

getUrl(init: boolean): string {

    return init ? url1 : url2;
}

我的问题是init并没有改变,所以URL还是一样。

我该如何解决?

正如我所说,由于我的代码,我不能使用this.init。

3 个答案:

答案 0 :(得分:1)

您的用例有点特殊,但是如果您真的想在流订阅期间更改变量,则可以将HttpClientimport { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; @Injectable() export class SampleService { API: string = "www.example.com/mmsg"; constructor(private http: HttpClient) {} update(): Observable<any> { let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); let params = new HttpParams().append('id': 1); let options = { headers: headers, params: params }; return this.http.put(this.API, null, options); } } 一起使用

BehaviorSubject

您随时可以通过withLatestFrom更改init $缓存的值

答案 1 :(得分:0)

在rxjs @ 6中,您可以将from作为独立函数使用:

从'rxjs'导入{from}; 另请参阅迁移到rxjs6指南

https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#import-paths

更新

您需要切换到管道语法,请确保从rxjs / operators中导入所有使用的运算符。例如:

从“ rxjs / operators”导入{map,filter,catchError,mergeMap};


getDataListApi(){     返回this.http.get(“ / api / method”)         管(            map((data:any [])=> {              this.products =数据; //在这里您可以根据需要更新数据              返回true;            }),catchError(error => {              return throwError('出问题了!')            });         ) }

答案 2 :(得分:0)

我解决了。 只需更改间隔中的开始并检查弗拉普地图中的值

getData(): Observable<any> {

   const refreshInterval = 5000;
   const interval = observableInterval(refreshInterval).pipe(startWith(-1)) 

   return interval.pipe(
      flatMap((index) => this.http.get<any>(this.getUrl(index))), 
      map((data) => this.doWhateverWithData(data)),
  );

}

getUrl(index: number): string {

   return (index === -1) ? url1 : url2;
}