首页 > 解决方案 > router.navigate 不工作并允许其下面的语句执行

问题描述

我在 中调用 2 种方法ngOnInit:一种方法检查路径参数,另一种方法在 url 中查找查询参数。

这是ngOnInit方法:

ngOnInit() {
  this.getFlavorAndService();
  this.getQueryParams();
}

这是查找路径参数的方法:

getFlavorAndService(): void {
    this.routePathParamsSubscription = this._route.params.subscribe(params => {
      const flavor: string = params.flavor;
      const service: string = params.service;

      if (flavor) {
        if (this._dataService.flavors.includes(flavor)) {
          this.flavor = flavor;
        } else {
          this._router.navigate(['/page-not-found']);
        }
      } else {
        this._router.navigate(['', this._dataService.DEFAULT_FLAVOR, this._dataService.DEFAULT_SERVICE]);
      }

      if (service) {
        if (this._dataService.isEdsService(service)) {
          this.service = service;
        } else {
          this._router.navigate(['/page-not-found']);
        }
      } else {
        this._router.navigate(['', this._dataService.DEFAULT_FLAVOR, this._dataService.DEFAULT_SERVICE]);
      }
    });
  }

这是查找查询参数的方法:

getQueryParams(): void {
  this.routeQueryParamsSubscription = this._route.queryParams.subscribe(queryParams => {
    ..... some code

    if (isEmpty(queryParams)) {
      this._router.navigate(['', this._dataService.flavor, this.service]);
    } else {
      this._router.navigate(['', this._dataService.flavor, this.service], { queryParams: queryParams, queryParamsHandling: 'merge' });
    }
  });
}

我的问题是,如果传递了无效的风味,我应该被重定向到/page-not-foundurl,并且根本不应该执行剩余的语句。相反,当我传递无效的风味或服务时,webapp 不会导航到page-not-found url,并且该方法的其余语句将被执行(来自 getQueryParams 方法)。它不会重定向,即使我使用return this._router.navigate(['/page-not-found']);.

应用程序不应该被导航到page-not-found并停止吗?

标签: angularangular7angular-routingangular-router

解决方案


只是为了确保构造函数应该是

import { ActivatedRoute, Router } from "@angular/router";
 constructor(private route: ActivatedRoute, private router: Router) {}

并使用 return this._router.navigate(['/page-not-found'])


推荐阅读