import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry, finalize } from 'rxjs/operators';
import { Router } from '@angular/router';
import { LoaderService } from '../components/loader/loader.service';
@Injectable()
export class HttpService {
private header = {
Headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}
constructor(
private httpClient: HttpClient,
private loaderService: LoaderService,
private router: Router
) { }
public get(url: string): Observable<any> {
(...)
}
public put(url: string, payload) {
(...)
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
if (error.status === 403) {
this.router.navigateByUrl('/access-denied');
}
return throwError(
'Please try again later.');
};
}
在错误处理程序中,如果错误代码为403,我想更改路由。此错误返回Cannot read属性'navigateByUrl'的未定义。我会弄乱上下文吗? 这样处理可以吗?