TypeScript - Angular 2 เปลี่ยนเส้นทางใน Interceptor เมื่อเกิดข้อผิดพลาด
ฉันได้เขียนวิธีการดักจับนี้แล้ว:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
console.log('EVENT:', event);
}, (err: HttpErrorResponse) => {
const message = err.error.message;
if (message == 'You need to activate your account!') {
// TODO: Redirect to '/auth/not-activated'
}
});
}
ถ้าฉันได้รับข้อความข้อผิดพลาดเฉพาะจากเซิร์ฟเวอร์ ฉันจำเป็นต้องเปลี่ยนเส้นทางผู้ใช้ไปยังที่อยู่ /auth/not activated
ฉันจะทำให้สำเร็จได้อย่างไร?
ฉันได้ลองแล้ว
this.router.navigateByUrl(url);
แต่นี่ใช้ไม่ได้
คำตอบ #1
ฉันได้แนะนำสิ่งเดียวกันนี้ในการตอบของฉันก่อนหน้านี้
ลงทะเบียนตัวดักจับเหมือนด้านล่าง
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { UnauthorizedInterceptor } from './../auth/UnauthorizedInterceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true
}
]
})
export class AppModule {}
อ่าน: ผู้ดักฟังที่ไม่ได้รับอนุญาตสำหรับ Angular
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(
private router: Router
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((err: any) => {
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['/login'], {
queryParams: {
redirectTo: document.location.pathname
}
});
// this response is handled
// stop the chain of handlers by returning empty
return Observable.empty();
}
// rethrow so other error handlers may pick this up
return Observable.throw(err);
});
}
ลองใช้สิ่งนี้ ใช้วิธี catch บน observable และใช้วิธี navigate สำหรับ route เพื่อไปยังหน้า
return next.handle(req).catch(
(err: HttpErrorResponse) => {
this.router.navigate(['/auth/not-activated']);
return Observable.throw(err);
});
