在 Angular HttpClient 拦截器中使用承诺
Use a promise in Angular HttpClient Interceptor
我可以在 HttpInterceptor
中使用 promise 吗?例如:
export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
.then((data)=>{
//do something with data and then
return next.handle(req);
});
}
为什么我需要这个?因为在向服务器发出请求之前,我需要获取一个令牌以添加到请求 header。
我的拦截器:
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
console.log('Intercepted!');
// return next.handle(req);
this.authService.getToken()
.then((token)=>{
console.log(token);
const reqClone = req.clone({
headers: req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json')
});
console.log(reqClone);
return next.handle(reqClone);
})
.catch((err)=>{
console.log('error in interceptor' + err);
return null;
});
}
}
要求:
this.http.post(this.baseURL + 'hero', data)
.subscribe(
(res: any) => {
console.log('Saved Successfully.');
console.log(res);
},
(err: any) => {
console.log('Save Error.' + err);
}
);
我面临的问题:
->我在解决承诺之前收到此错误。
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Promise resloves 我得到了我的令牌,但是在错误之后。
更新:使用 rxjs@6.x
import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService){}
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return from(this.authService.getToken())
.pipe(
switchMap(token => {
const headers = request.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const requestClone = request.clone({
headers
});
return next.handle(requestClone);
})
);
}
}
原始答案
是的,你可以在拦截器的构造方法中注入所需的服务,并在intercept
的实现中检索值,创建一个新的更新的http请求并处理它。
我不擅长承诺,所以你可以尝试以下方法:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
});
}
}
对于 RxJS 6+ 我已经更新了 Jota.Toledo 的答案:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.pipe(switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
}));
}
}
轮到我了(感谢 Jota.Toledo 和 Capripio):
1) 将 "fromPromise" 切换为 "from" -->
2) 修复 'application/json' 引用
import { Observable, from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.authService.getToken()).pipe(
switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
}));
}
}
我的 RxJs 版本:“6.2.2”
希望对您有所帮助!
我可以在 HttpInterceptor
中使用 promise 吗?例如:
export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
.then((data)=>{
//do something with data and then
return next.handle(req);
});
}
为什么我需要这个?因为在向服务器发出请求之前,我需要获取一个令牌以添加到请求 header。
我的拦截器:
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
console.log('Intercepted!');
// return next.handle(req);
this.authService.getToken()
.then((token)=>{
console.log(token);
const reqClone = req.clone({
headers: req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json')
});
console.log(reqClone);
return next.handle(reqClone);
})
.catch((err)=>{
console.log('error in interceptor' + err);
return null;
});
}
}
要求:
this.http.post(this.baseURL + 'hero', data)
.subscribe(
(res: any) => {
console.log('Saved Successfully.');
console.log(res);
},
(err: any) => {
console.log('Save Error.' + err);
}
);
我面临的问题:
->我在解决承诺之前收到此错误。
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Promise resloves 我得到了我的令牌,但是在错误之后。
更新:使用 rxjs@6.x
import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService){}
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return from(this.authService.getToken())
.pipe(
switchMap(token => {
const headers = request.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const requestClone = request.clone({
headers
});
return next.handle(requestClone);
})
);
}
}
原始答案
是的,你可以在拦截器的构造方法中注入所需的服务,并在intercept
的实现中检索值,创建一个新的更新的http请求并处理它。
我不擅长承诺,所以你可以尝试以下方法:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
});
}
}
对于 RxJS 6+ 我已经更新了 Jota.Toledo 的答案:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.pipe(switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
}));
}
}
轮到我了(感谢 Jota.Toledo 和 Capripio):
1) 将 "fromPromise" 切换为 "from" -->
2) 修复 'application/json' 引用
import { Observable, from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.authService.getToken()).pipe(
switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
}));
}
}
我的 RxJs 版本:“6.2.2” 希望对您有所帮助!