从应用中直接输入的 url 中读取路由参数

Read route params from directly entered url in app

我的问题是关于 angular 4,如何获取路由参数,例如,如果用户访问您的页面而不是默认的 url,例如 [=13] =],到 http://localhost:3000/user/:id 之类的东西,并能够从 url 中获取 :id(用户直接在浏览器中输入它,而不是通过应用程序导航)。

在下面的示例中使用了相同的组件,主要是因为需要捕获该 id 并调度其他操作,如果它存在,就可以了。

我试过 ActivatedRoute 但据我所知,只有在整个应用程序中导航时才有效,从应用程序内部,而不是在这种情况下,它总是 returns 如果 url 直接在浏览器中输入,则为空值,它将被重定向到默认的 / 路由,就是这样。

非常感谢任何提示或指示

app.routing-module.ts

import {hookComponent} from './hook.component';
import {RouterModule, Routes} from '@angular/router';
import {NgModule} from '@angular/core';

export const routes: Routes = [
  {
    path: '',
    component: HookComponent
  },
  {
    path: 'user/:id',
    component: HookComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: true })],
  exports: [RouterModule]
})
export class AppRoutingModule {}

hook.component

import {Component, EventEmitter, Input, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, ParamMap} from '@angular/router';

@Component({
  selector: 'hook',
  templateUrl: 'hook.component.html',
  styleUrls: ['hook.component.scss']
})
export class HookComponent implements OnDestroy, OnInit {
  constructor(private route: ActivatedRoute) {
    
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       console.log('params are', params); //null?
    });

  }
}

通过Location

访问当前url
public  constructor(location:Location) {
  let url = location.prepareExternalUrl(location.path());
}

并从中解析出id

你的方法已经可以了,但在你的例子中 params 是一个数组,你可以通过调用 params['id']:

来访问 :id
this.sub = this.route.params.subscribe(params => {
  console.log('params are', params['id']);
});

Here 是 stackblitz 上的一个工作示例。

如果您只想记录 params.id;尝试像这样使用 ActivatedRouteSnapshot

  ngOnInit() {
    console.log(this.route.snapshot.params.id);
}

如果你想检查 params.id 是否存在,可以这样做:

import {Component, EventEmitter, Input, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, ParamMap} from '@angular/router';

@Component({
  selector: 'hook',
  templateUrl: 'hook.component.html',
  styleUrls: ['hook.component.scss']
})
export class HookComponent implements OnDestroy, OnInit {

  hasId: boolean = false;
  constructor(private route: ActivatedRoute) {

  }

  ngOnInit() {
    if(this.route.snapshot.params.id !== null)
    {
        // do magic....
    }
  }
}