从应用程序中直接输入的URL读取路径参数

时间:2018-02-01 13:22:38

标签: javascript angular angular4-router

我的问题是关于角度4,如何获取路线参数,例如,如果用户在您的网页上使用而不是默认网址(例如http://localhost:3000/),则为{{1} },并且能够从该网址中获取http://localhost:3000/user/:id(用户已在浏览器中直接输入,而不是在应用中导航)。

在示例中,使用相同的组件,主要是因为需要捕获该id并发送其他操作(如果存在),那就是它。

我尝试过使用:id但是从目前为止我所知道的,只有在整个应用程序中导航时,才能在应用程序内部工作,而不是在这种情况下,如果是这样的话,它总会返回空值url直接在浏览器中输入,它会被重定向到默认的ActivatedRoute路由,就可以了。

非常感谢任何提示或指示

app.routing-module.ts



/




hook.component



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 {}




3 个答案:

答案 0 :(得分:1)

通过url

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

并从中解析id

答案 1 :(得分:1)

您的方式已经可以,但在您的示例中params是一个数组,您可以通过调用:id访问params['id']

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

Here是stackblitz的一个工作示例。

答案 2 :(得分:0)

如果您只想记录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....
    }
  }
}
相关问题