Angular 6-激活路线-为什么我无法从路线中提取ID?

时间:2019-01-10 18:03:19

标签: angular typescript

我在使用paramMap从路由中获取ID并将其存储在变量中时遇到问题。它将评估为空。

this.route.paramMap.subscribe((params: ParamMap) => {
  this.current_id = params.get('SiteHid')
  console.log(this.current_id)
})

^ this.current_id记录为空。我哪里可能出问题了?

它正在尝试从“ sites /:siteHid”路由中提取ID。

我的路由模块中的路由如下:

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' }, // default route
  { path: 'login', component: LoginComponent },
  { path: 'applications', component: ApplicationsComponent, canActivate: [AuthGuard] },
  { path: 'sites/:siteHid', component: SiteComponent, canActivate: [AuthGuard]},
  { path: 'sites', component: SitesComponent, canActivate: [AuthGuard] },
  { path: 'sites-map', component: MapSitesComponent, canActivate: [AuthGuard] },
  { path: 'site-map/:siteHid', component: MapSiteComponent, canActivate: [AuthGuard] },
  { path: 'site-settings/:siteHid', component: MapSiteComponent, canActivate: [AuthGuard] },
  { path: 'devices/:deviceHid', component: DeviceComponent, canActivate: [AuthGuard] },
  { path: 'devices', component: DevicesComponent, canActivate: [AuthGuard] },
  { path: '**', component: PageNotFoundComponent} // should always be the last
];

整个组件如下:

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
  is_general_route;
  current_id;
  has_id;

  constructor(private route: ActivatedRoute, private router: Router) { }

 ngOnInit() {
    this.is_general_route = false;
    this.has_id = false;

   function hasNumber(myString) {
      return /\d/.test(myString);
   }
    this.is_general_route = hasNumber(this.router.url)

    this.route.paramMap.subscribe((params: ParamMap) => {
      this.current_id = params.get('SiteHid')
      this.has_id = true;
      console.log(this.current_id)
    })
    //^^ this evaluates the route to see if it contains any numbers/ids. If it does not have any id's, this.is_general_route is false, 
    //meaning the current page does not display the nav tabs that are needed for a singular site. It can display the 'all sites' and 'all sites map' tabs.
    //Otherwise, it's true, and the nav component knows to display 'current site' and 'singular site map' tabs
  }

}

这可能是哪里出了问题?非常感谢!让我知道是否可以澄清任何事情。

1 个答案:

答案 0 :(得分:1)

使用this.current_id = params.get('siteHid')代替 SiteHid

这是由于大小写敏感:)