【问题标题】:rxjs: change HttpRequest using a rxjs custom operatorrxjs:使用 rxjs 自定义运算符更改 HttpRequest
【发布时间】:2019-02-03 10:30:52
【问题描述】:

我想创建一个自定义运算符 (caching) 来为 `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

【问题讨论】:

  • 算子转换 observables 的发射,所以没有。你在这里所做的是一个不应该工作的黑客,只是由于实施细节。
  • 我认为你应该通过改变 Rest 服务的工作方式来寻找解决方案的方向。看起来有人试图概括无法概括的东西。或者,查看 HTTP 拦截器,手动设置缓存标头。

标签: angular rxjs angular-httpclient


【解决方案1】:

我个人认为你过度设计了这个,为什么不创建一个从 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 请求

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多