rxjs:使用rxjs自定义运算符更改HttpRequest

时间:2019-02-03 10:30:53

标签: angular rxjs angular-httpclient

我想创建自定义操作符(caching)到新PARAMS添加到`的HttpRequest。

const caching = (opt: {maxCacheAge: number} = {maxCacheAge: 30}) => (source: Observable<any>) =>
  new Observable(observer => {

    /*
     * I found the HttpRequest at this level!!!
     */
    const httpRequest = source.source.source.source.value as HttpRequest<any>;     
    const req = httpRequest.clone({
      setParams: {
        maxCacheAge: opt.maxCacheAge.toString()
      }
    });    

    source.source.source.source.value = req;
    /*
     * Here the HttpRequest is changed correctly, 
     * but into HttpInterceptor there is the original request.
     *
     * Moreover, `source` is an internal implementation so is deprecated
     */
    console.log('obs:', source);

    return source.subscribe({
      next(res) { observer.next(res); },
      error(err) { observer.error(err); },
      complete() { observer.complete(); }
    });
  });



@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private rest: Rest) {
    this.getCapital('rome').subscribe(res => {
      console.log('res', res);
    });
  }

  getCapital(name: string): Observable<any> {
    return this.rest.get(`https://restcountries.eu/rest/v2/capital/${name}`).pipe(
      caching()
    );
  }

}

是否可以使用rxjs更改请求?

我正在使用Angular 7.2和rxjs 6.3

1 个答案:

答案 0 :(得分:0)

就我个人而言,我认为您对此进行了过度设计,为什么不制作一个从 localStorage 获取数据或设置数据(如果现在不存在)的服务

getCache<T = any>(key:string>:T{
  let cachedValue = this.transferState.get(stateKey, null);
  //check local storage and create state value from there
  if(cachedValue === null){
    cachedValue = localStorage.getItem(key) 
    this.transferState.set(stateKey, cachedValue);
  }
  return cachedValue;
}

然后用

调用它
data = this.serviceName.getCache("keyName")

如果您的缓存中没有数据可以开始,您可能需要构建您的 get 请求,尽管它是空的