angular - 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-found
url,并且根本不应该执行剩余的语句。相反,当我传递无效的风味或服务时,webapp 不会导航到page-not-found url,并且该方法的其余语句将被执行(来自 getQueryParams 方法)。它不会重定向,即使我使用return this._router.navigate(['/page-not-found']);
.
应用程序不应该被导航到page-not-found
并停止吗?
解决方案
只是为了确保构造函数应该是
import { ActivatedRoute, Router } from "@angular/router";
constructor(private route: ActivatedRoute, private router: Router) {}
并使用 return this._router.navigate(['/page-not-found'
])
推荐阅读
- php - 如何查找特定于服务器的 wkhtmltopdf 设置?
- nginx - Nginx 一域加二项目——后端&前端
- python - 简化 Python 字典理解
- python - ValueError:在python3中解包的值太多(预期为2)
- excel - Excel INDIRECT 函数范围无效
- python - 如何使用 python 控制包正确绘制 MIMO 系统的阶跃响应
- java - JDialog在javafx中的swingnode内空白
- flutter - 保持按钮禁用直到特定时间 - Flutter
- mysql - beforeCreate 挂钩更改未保存到数据库
- ruby-on-rails - Rails s 因为宝石而不再工作?