Read route params from directly entered url in app

拜拜、爱过 提交于 2019-12-02 08:12:36

Your way is already ok, but in your example params is an array and you can access to :id by calling params['id']:

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

Here is an working example on stackblitz.

Access current url via Location

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

and parse out id from this.

If all you want to do is log the params.id; try using the ActivatedRouteSnapshot like this.

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

If you want to check if the params.id is present, maybe do something like:

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....
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!