[英]Can anyone explain exhaustMap in rxjs?
import {
HttpHandler,
HttpInterceptor,
HttpParams,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { exhaustMap, take } from 'rxjs/operators';
import { AuthenticationService } from './authentication.service';
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: AuthenticationService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
return this.authService.emitUser.pipe(
take(1),
exhaustMap((user) => {
if (!user) {
return next.handle(req);
}
const modifiedReq = req.clone({
params: new HttpParams().set('auth', user!.token!),
});
return next.handle(modifiedReq);
})
);
}
}
This is an interceptor file which modifies the request url by adding 'auth' query params and a value as a token that we get from the user object here.这是一个拦截器文件,它通过添加“auth”查询参数和一个我们从用户 object 获得的令牌值来修改请求 url。 But I cannot understand what is happending inside the exhaustMap.
但我无法理解 exhaustMap 内部发生了什么。
exhaustMap
is a higher order pipe operator, which subscribes to the piped observable and for (nearly) each emitted value, returns a new observable, coming from the function you passed to it. exhaustMap
是更高阶的 pipe 运算符,它订阅管道可观察对象,并且(几乎)每个发出的值,返回一个新的可观察对象,来自您传递给它的 function。
But what should happen if the returned observable has not completed yet, but the source observable emits a new value.但是如果返回的 observable 还没有完成,但是源 observable 发出了一个新值,应该会发生什么。 That's where
exhaustMap
, switchMap
, concatMap
and mergeMap
differ.这就是
exhaustMap
、 switchMap
、 concatMap
和mergeMap
不同的地方。
In your case exhaustMap
is used, which means if a new value is coming from the source observable, but the previously mapped observable is not yet completed, the new value coming from the source observable will be ignored.在您的情况下,使用了
exhaustMap
,这意味着如果新值来自源 observable,但先前映射的 observable 尚未完成,则来自源 observable 的新值将被忽略。
It will be ignored until the previously returned observable has completed.在先前返回的可观察对象完成之前,它将被忽略。 After that new values from the source observable will be mapped to the inner observable again.
之后,源 observable 的新值将再次映射到内部 observable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.