Angular 7:ActivateRoute catch paramId get null value

问题描述 投票:0回答:1

我想在页面加载时订阅我的praramID,但我尝试console.log()它返回null。我正在使用Angular 7。

这是我的打字稿:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from "@angular/router";
    @Component({
     selector: 'c:navbar',
     templateUrl: './navbar.component.html',
     styleUrls: ['./navbar.component.scss']
    })
    export class NavbarComponent implements OnInit {
     selectedItem: string;
     selectedFlag: string;
     paramsId: any;
    constructor(private _ActivateRoute: ActivatedRoute) { }

    ngOnInit() {
    this._ActivateRoute.paramMap.subscribe(params => {
    this.paramsId = params.get("activeLang");
    console.log('Get Param',this.paramsId);
    });
   }

这是我的路线:

   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';
   import { HomePagesComponent } from './pages/home-pages/home- 
    pages.component';
   import { PersonalPagesComponent } from './pages/personal- 
    pages/personal-pages.component';


   const routes: Routes = [
  {path: '', redirectTo: 'en/home', pathMatch: 'full'},
  {path: ':activeLang/home', component: HomePagesComponent},
  {path: ':activeLang/personal', component: PersonalPagesComponent},
  {path: ':activeLang/business', component: BusinessPagesComponent},
   ];

   @NgModule({
   imports: [RouterModule.forRoot(routes, {scrollPositionRestoration: 
             'enabled'})],
   exports: [RouterModule]
   })
   export class AppRoutingModule { }

我不确定我的代码是否正确,但是当我尝试null时它返回console.log()你们能帮我弄清楚吗?

应该在控制台中返回。

typescript angular7 angular7-router angular-activatedroute
1个回答
0
投票

我认为您应该尝试以下操作:

this.paramsId = this._ActivateRoute.snapshot.paramMap.get("activeLang");
console.log(this.paramsId);
© www.soinside.com 2019 - 2024. All rights reserved.