Перенаправление, если Resolve failed Angular 2
Как я могу перенаправить на другую страницу, если сбой в Angular 2?
Я называю это решение для моей страницы редактирования, но я хочу обрабатывать ошибки на странице "Решить"
Мое решение:
resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean {
return new Promise((resolve, reject) => {
if (route.params['id'] !== undefined) {
this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
.subscribe(
result => {
console.log("ok");
return resolve(result);
},
error => {
return resolve(error);
});
}});
Ответы
Ответ 1
Как и в документах, вызывая this.router.navigate(["url"])
... (подумайте, чтобы добавить Router
в ваш конструктор)
class MyResolve {
constructor(private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable <any> {
return this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
.pipe(catchError(err => {
this.router.navigate(["/404"]);
return EMPTY;
}));
}
}
Ответ 2
Другое решение: если вы хотите применить стратегию перенаправления после сбоя для ВСЕХ ваших распознавателей, вы можете перехватить событие маршрутизатора и применить перенаправление в случае сбоя. Вот код, который вы можете добавить в свой AppComponent:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Router, RouterEvent, NavigationError } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private cdr: ChangeDetectorRef
){}
ngOnInit() {
this.router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event)
});
}
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationError) {
this.router.navigate(["error"],{ queryParams: { redirect: event.url } });
}
this.cdr.detectChanges();
}
}