本文介绍了在Angular 2中同时订阅路由参数和queryParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了以下路由系统

export const MyRoutes: Routes = [
    {path: '', redirectTo: 'new', pathMatch: 'full'},
    {path: ':type', component: MyComponent}
];

并具有以下导航系统

goToPage('new');
goToPageNo('new', 2);

goToPage(type) {
    this.router.navigate([type]);
}
goToPageNo(type, pageNo) {
    this.router.navigate([type], {queryParams: {page: pageNo}});
}

示例 URL 如下

http://localhost:3000/new?page = 2

http://localhost:3000/updated

http://localhost:3000/updated?page = 5

有时它们具有可选 queryParams (页面)

Sometimes they have optional queryParams (page)

现在,我需要同时阅读 route参数和queryParams

Now I need to read both route params and queryParams

ngOnInit(): void {
    this.paramsSubscription = this.route.params.subscribe((param: any) => {
        this.type = param['type'];
        this.querySubscription = this.route.queryParams.subscribe((queryParam: any) => {
            this.page = queryParam['page'];
            if (this.page)
                this.goToPageNo(this.type, this.page);
            else
                this.goToPage(this.type);
        });
    });
}

ngOnDestroy(): void {
    this.paramsSubscription.unsubscribe();
    this.querySubscription.unsubscribe();
}

现在这不能按预期方式工作,访问没有queryParams的页面可以正常工作,然后我访问带有queryParams的页面"goToPageNo"被多次调用,因为我正在订阅路由参数内的queryParams.

Now this is not working as expected, visiting pages without queryParams works, then of I visit a page with queryParams "goToPageNo" gets called multiple times, as I am subscribing to queryParams inside route params.

我查看了Angular 2文档,它们没有任何示例或代码,这些示例或代码同时实现了对路由参数和queryParams 的订阅.

I looked at the Angular 2 documentation, they do not have any example or codes where a subscription to both route params and queryParams is implemented at the same time.

有什么办法可以正确地做到这一点?有什么建议吗?

Any way to do this properly? Any suggestions?

推荐答案

对于Angular 6 +

For Angular 6+

import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

...

combineLatest(this.route.params, this.route.queryParams)
    .pipe(map(results => ({params: results[0].xxx, query: results[1]})))
    .subscribe(results => {
        console.log(results);
    });

xxx来自您的路线

{path: 'post/:xxx', component: MyComponent},

这篇关于在Angular 2中同时订阅路由参数和queryParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 19:44