代码之家  ›  专栏  ›  技术社区  ›  Jerald

订阅路由参数不起作用

  •  1
  • Jerald  · 技术社区  · 6 年前

    我有一页 /news 带参数 page . 例如: /news;page=2 . 我不想在页面更改时重新初始化新闻页面。我只想订阅页面更改,我尝试了以下代码:

    export class NewsPage implements OnInit {
        constructor(private route: ActivatedRoute) {
        }
    
        ngOnInit() {
            this.route.params.subscribe(params => {
                ...
            });
        }
    }
    

    如果 新闻 页面打开,我导航到 新闻 具有不同页参数的页( this.router.navigate(['/news', {page: 2} ]) )然后重新初始化该页(该页将被销毁并重新创建)。

    但如果我用queryparams( /news?page=2 )而不是参数( 新闻;页面=2 )然后一切正常:

    export class NewsPage implements OnInit {
        constructor() {
        }
    
        ngOnInit() {
            this.route.queryParams.subscribe(params => {
                ...
            });
        }
    }
    

    如果我打电话 this.router.navigate(['/news'], {queryParams: {page: 2}} ) 然后该页将不会被重新初始化。只执行订阅回调。为什么会这样?

    这是我的路由文件:

    const routes: Routes = [
      { path: "", redirectTo: "/home", pathMatch: "full" },
      {
        path: "news",
        loadChildren: "./pages/news/news.module#NewsPageModule"
      }
      { path: "**", redirectTo: "/page404" }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    

    这是我的新闻页面模块:

    const routes: Routes = [
      {
        path: "",
        component: NewsPage
      }
    ];
    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        IonicModule,
        RouterModule.forChild(routes),
        SharedModule
      ],
      declarations: [NewsPage]
    })
    export class NewsPageModule {}
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   rijin    6 年前

    更新导航函数调用:)

     this.router.navigate(['/news'], { queryParams: { page: 2 } });
    

    然后

    export class NewsPage implements OnInit {
        constructor(private route: ActivatedRoute) {
        }
    
        ngOnInit() {
            this.route.queryParams.subscribe(params => {
                ...
            });
        }
    }