从 URL 路径读取变量

Read variable from URL path

我正在尝试从 Angular 中的 URL 中读取一个变量。

我的路线中有这个

const routes: Routes = [
  { path: ':page', component: BlogComponent}
];

这在我的博客组件构造函数中。

this.route.paramMap.subscribe(params => {
  const page = params.params.page;
  cacheService
    .getAllPostIds()
    .subscribe(postIds => this.loadPage(cacheService, postIds, page)
  );
});

如果有参数,即 www.url.com/1 returns page = 1.

如果 url 之后没有任何内容(只有 www.url.com),但是 永远不会 触发路由订阅。这是订阅 url 变量和更改的正确方法吗,如果不是,我应该怎么做,如果是,即使只有空白 url /

用 2 条路线解决了。

const routes: Routes = [
  { path: '', component: BlogComponent, pathMatch: 'full' },
  { path: ':page', component: BlogComponent, pathMatch: 'full' },
];

和这样的构造函数:

constructor(private cacheService: CacheService, private route: ActivatedRoute) {
  this.route.paramMap.subscribe(params => {
    let page = params.params.page;
    if (page == null){
      page = 1;
    }
    console.log('page: ' + page);
    cacheService
      .getAllPostIds()
      .subscribe(postIds => this.loadPage(cacheService, postIds, params.params.page)
    );
  });
}

原来的路径在:page没有参数的时候没有被命中,然后添加使得构造函数在没有页面时默认为1。

不确定这是否是最好的方法。

我正在使用波纹管代码被动地获取路由参数。

constructor ( private route: ActivatedRoute) {}

ngOnInit() {

this.route.params.subscribe(
    (params) => {
        this.page = params[‘page’];
    }
  );
}