我有一个用例,我需要限制传出 http 请求的数量。是的,我确实在服务器端有速率限制器,但前端也需要限制活动 http 请求的数量。因此,我正在尝试实现一个滑动窗口协议,在任何时候我都会只有 n 个活跃请求。
这种使用 Rxjs 的方法通常工作得很好,请参见此处: https: //jsbin.com/pacicubeci/1/edit ?js,console,output
但我不清楚如何对 http 拦截器使用相同的逻辑。我的以下尝试在编译时失败,并出现以下错误:
“Subscription”类型缺少“Observable<HttpEvent>”类型中的以下属性:_isScalar、source、operator、lift 以及其他 114 个属性。(2740)
这样,我怎样才能返回一个可观察对象并同时在http拦截器中维护一个队列?我的方法有缺陷吗?我可以使用 http 拦截器来限制 http 速率吗?
@Injectable()
export class I1 implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const modified = req.clone({ setHeaders: { "Custom-Header-1": "1" } });
return next
.handle(req)
.do((ev: HttpEvent<any>) => {
if (ev instanceof HttpResponse) {
console.log(ev);
}
})
.pipe(
bufferTime(1000, null, 1),
filter(buffer => buffer.length > 0),
concatMap(buffer => of(buffer).pipe(delay(1000)))
)
.subscribe(console.log);
} …Run Code Online (Sandbox Code Playgroud) sliding-window rxjs angular-http-interceptors angular rxjs-subscriptions
有很多方法可以在一个组件中有效地处理多个订阅,我在这里有 2 种方法,想知道哪种方法更有效,为什么?
第 1 步:创建数组
private subscriptionArray: Subscription[];
Run Code Online (Sandbox Code Playgroud)
第 2 步:向数组添加订阅
this.subscriptionArray.push(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
this._toast.success('New store created');
}));
Run Code Online (Sandbox Code Playgroud)
第 3 步:迭代每个订阅和取消订阅
this.subscriptionArray.forEach(subs => subs.unsubscribe());
Run Code Online (Sandbox Code Playgroud)
第 1 步:创建新订阅
private subscriptions = new Subscription();
Run Code Online (Sandbox Code Playgroud)
第 2 步:添加订阅
this.subscriptions.add(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
this._toast.success('New store created');
this._router.navigate(['/store-management']);
}));
Run Code Online (Sandbox Code Playgroud)
Step3:清除订阅
this.subscriptions.unsubscribe();
Run Code Online (Sandbox Code Playgroud) 无法弄清楚如何根据条件语句订阅 Angular 服务所需的方法
// this.someService.someMethod depending on the conditional statement
.pipe(takeUntil(this.unsubscribe$))
.subscribe((items) => {
this.someData = items;
});
Run Code Online (Sandbox Code Playgroud)