如果您想了解更多关于拦截器和 HttpClientModule 如何在后台工作的信息,您可以查看这篇文章:Exploring the HttpClientModule in Angular。
我的方法有缺陷吗?
在这种情况下,问题在于 next.handle 应该返回一个 Observable,但通过订阅它,它返回一个 Subscription。
为了更好地理解原因,我将粘贴从上面链接的文章中复制的 sn-p:
const obsBE$ = new Observable(obs => {
timer(1000)
.subscribe(() => {
// console.log('%c [OBSERVABLE]', 'color: red;');
obs.next({ response: { data: ['foo', 'bar'] } });
// Stop receiving values!
obs.complete();
})
return () => {
console.warn("I've had enough values!");
}
});
// Composing interceptors the chain
const obsI1$ = obsBE$
.pipe(
tap(() => console.log('%c [i1]', 'color: blue;')),
map(r => ({ ...r, i1: 'intercepted by i1!' }))
);
let retryCnt = 0;
const obsI2$ = obsI1$
.pipe(
tap(() => console.log('%c [i2]', 'color: green;')),
map(r => {
if (++retryCnt <=3) {
throw new Error('err!')
}
return r;
}),
catchError((err, caught) => {
return getRefreshToken()
.pipe(
switchMap(() => /* obsI2$ */caught),
)
})
);
const obsI3$ = obsI2$
.pipe(
tap(() => console.log('%c [i3]', 'color: orange;')),
map(r => ({ ...r, i3: 'intercepted by i3!' }))
);
function getRefreshToken () {
return timer(1500)
.pipe(q
map(() => ({ token: 'TOKEN HERE' })),
);
}
function get () {
return obsI3$
}
get()
.subscribe(console.log)
/*
-->
[i1]
[i2]
I've had enough values!
[i1]
[i2]
I've had enough values!
[i1]
[i2]
I've had enough values!
[i1]
[i2]
[i3]
{
"response": {
"data": [
"foo",
"bar"
]
},
"i1": "intercepted by i1!",
"i3": "intercepted by i3!"
}
I've had enough values!
*/
StackBlitz demo.
要点是拦截器创建某种链,其以负责发出实际请求的可观察对象结束。 This 是链中的最后一个节点:
return new Observable((observer: Observer<HttpEvent<any>>) => {
// Start by setting up the XHR object with request method, URL, and withCredentials flag.
const xhr = this.xhrFactory.build();
xhr.open(req.method, req.urlWithParams);
if (!!req.withCredentials) {
xhr.withCredentials = true;
}
/* ... */
})
如何在 http 拦截器上同时返回一个 observable 并维护一个队列
我认为解决这个问题的一种方法是创建一个包含队列逻辑的拦截器,并使其intercept 方法返回一个Observable,以便它可以被订阅:
const queueSubject = new Subject<Observable>();
const pendingQueue$ = queueSubject.pipe(
// using `mergeAll` because the Subject's `values` are Observables
mergeAll(limit),
share(),
);
intercept (req, next) {
// `next.handle(req)` - it's fine to do this, no request will fire until the observable is subscribed
queueSubject.next(
next.handle(req)
.pipe(
// not interested in `Sent` events
filter(ev => ev instanceof HttpResponse),
filter(resp => resp.url === req.url),
)
);
return pendingQueue$;
}
之所以使用filter 运算符,是因为通过使用share,响应将发送给所有订阅者。假设你同步调用http.get 5 次,所以share 的主题有5 个新订阅者,最后一个会收到它的响应,但也会收到其他请求的响应。所以使用可以使用filter来给请求正确的响应,在这种情况下,通过比较请求的URL(req.url)和我们从HttpResponse.url得到的URL:
observer.next(new HttpResponse({
body,
headers,
status,
statusText,
url: url || undefined,
}));
Link for the above snippet.
现在,我们为什么要使用share()?
让我们先看一个更简单的例子:
const s = new Subject();
const queue$ = s.pipe(
mergeAll()
)
function intercept (req) {
s.next(of(req));
return queue$
}
// making request 1
intercept({ url: 'req 1' }).subscribe();
// making request 2
intercept({ url: 'req 2' }).subscribe();
// making request 3
intercept({ url: 'req 3' }).subscribe();
此时,主题 s 应该有 3 个订阅者。这是因为当您返回队列时,您会返回 s.pipe(...),而当您订阅 时,它与执行操作相同:
s.pipe(/* ... */).subscribe()
所以,这就是主题最后会有 3 个订阅者的原因。
现在让我们检查相同的 sn-p,但使用 share():
const queue$ = s.pipe(
mergeAll(),
share()
);
// making request 1
intercept({ url: 'req 1' }).subscribe();
// making request 2
intercept({ url: 'req 2' }).subscribe();
// making request 3
intercept({ url: 'req 3' }).subscribe();
订阅请求 1 后,share 将创建一个 Subject 实例,并且所有后续订阅者都将属于它,而不是属于 main Subject s。因此,s 将只有一个订阅者。这将确保我们正确实现队列,因为尽管主题 s 只有一个订阅者,它仍然会接受 s.next() 值,其结果将传递给另一个主题(来自 @987654354 的那个) @),它最终会将响应发送给它的所有订阅者。