Read route params from directly entered url in app

后端 未结 3 802
萌比男神i
萌比男神i 2021-01-28 08:49

My question would be regarding angular 4, how to get route params, if for example a user gets on your page with, instead of the default url, like for example http://localh

相关标签:
3条回答
  • 2021-01-28 08:59

    Access current url via Location

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

    and parse out id from this.

    0 讨论(0)
  • 2021-01-28 09:11

    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....
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-28 09:20

    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.

    0 讨论(0)
提交回复
热议问题