如果Resolve失败,则重定向Angular 2

时间:2017-03-29 14:54:47

标签: angular angular2-routing

如果Angular 2中的解析失败,如何重定向到另一个页面? 我将此解析称为我的编辑页面,但我想处理Resolve页面中的错误

我的决心:

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

2 个答案:

答案 0 :(得分:23)

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

答案 1 :(得分:0)

另一种解决方案,如果要在对所有解析程序进行故障转移后应用重定向策略,则可以拦截路由器事件,并在故障事件上应用重定向。您可以在此处在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();
  }

}