如果 Resolve 失败则重定向 Angular 2

Redirect if Resolve fails Angular 2

如果 Angular2 中解析失败,如何重定向到另一个页面? 我为我的编辑页面调用此解析,但我想处理解析页面中的错误

我的决心:

 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);
            });
    }});

就像in the docs一样,调用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;
      }));
  }
}

另一个解决方案,如果您想在所有解析器失败后应用重定向策略,您可以拦截路由器事件并在失败事件上应用重定向。您可以在 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();
  }

}