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

问题描述 投票:14回答:2

如果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);
            });
    }});
angular angular2-routing
2个回答
27
投票

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

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

}
© www.soinside.com 2019 - 2024. All rights reserved.