[英]rxjs: change HttpRequest using a rxjs custom operator
I want to create a custom operator ( caching
) to add new params to `HttpRequest.我想创建一个自定义运算符( 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()
);
}
}
Is it possibile change the request using rxjs?是否可以使用 rxjs 更改请求?
I'm Using Angular 7.2 and rxjs 6.3我正在使用 Angular 7.2 和 rxjs 6.3
Personally I think you're over engineering this, why not make a service that gets data from localStorage or sets data if it's not there now就我个人而言,我认为您对此进行了过度设计,为什么不制作一个从 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;
}
then call it with然后用
data = this.serviceName.getCache("keyName")
You may need to build in your get request if there isn't data in your cache to start with though it's null如果您的缓存中没有数据可以开始,您可能需要构建您的 get 请求,尽管它为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.