在Angular 2中同时订阅路由参数和queryParams

Shifatul:

我已经建立了以下路由系统

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

示例网址如下所示

http:// localhost:3000 / new

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

http:// localhost:3000 /更新

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

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

现在我需要阅读路由参数和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。

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

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

Shifatul:

对于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},

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章