【发布时间】: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