我很欣赏 Tjaart van der Walt 关于如何解决 Angular/rxjs7++ 中引入的“重大变化”的回应。但是我在尝试将他的响应应用于我的 Angular 拦截器时仍然遇到了几个问题:
这是更新的代码(未能编译的部分标记为“OLD”)
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpResponse} from '@angular/common/http';
import {HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
/*
OLD:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
*/
import { Observable } from 'rxjs';
import { of } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { AuthService } from './auth.service';
@Injectable()
export class StockAppInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService.authToken) {
const authReq = req.clone({
headers: req.headers.set(
'Authorization',
this.authService.authToken
)
});
console.log('Making an authorized request');
req = authReq;
}
/*
* OLD:
* return next.handle(req)
* .do(event => this.handleResponse(req, event),
* error => this.handleError(req, error));
*/
return next.handle(req).pipe(
tap(
event => this.handleResponse(req, event),
error => this.handleError(req, error)
)
);
}
handleResponse(req: HttpRequest<any>, event) {
console.log('Handling response for ', req.url, event);
if (event instanceof HttpResponse) {
console.log('Request for ', req.url,
' Response Status ', event.status,
' With body ', event.body);
}
}
handleError(req: HttpRequest<any>, event) {
console.error('Request for ', req.url,
' Response Status ', event.status,
' With error ', event.error);
}
}
所需的更改包括更改import
路径和替换pipe()
,tap()
和of()
.
此链接也是 RxJS6 更改的一个很好的资源:
https://www.academind.com/learn/javascript/rxjs-6-what-changed/