Angular 4/5 - route paramMap vs params

2020-02-05 05:52发布

问题:

I am trying to get URL param in my Angular 5 app and I've found two ways of doing it:

1) Using paramMap

    ngOnInit() {
      this.hero$ = this.route.paramMap
        .switchMap((params: ParamMap) =>
          this.service.getHero(params.get('id')));
    }

2) Using params

    ngOnInit() {
      this.sub = this.route.params.subscribe(params => {
        this.id = +params['id'];
      });
    }

Is there any difference? Which one is the best practice?

回答1:

According to the documentation :

Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.

params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

Simple and efficient !



回答2:

Actually there is no difference but params is pretty old and may be deprecated soon

paramMap

An Observable that contains a map of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter.

queryParamMap

An Observable that contains a map of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter.



回答3:

Note : The paramMap provide more convenience to play with route parameter. Having following three methods:

  1. has()
  2. get()
  3. getAll()

has() : Example :

    this.router.navigate(['example', id]); 

     this.activatedRoute.paramMap.subscribe(params => {
          console.log(params.has('id')); // true
        })

get() : Example :

       this.router.navigate(['example', "id","another ID"]); 

     this.activatedRoute.paramMap.subscribe(params => {
          console.log(params.get('id'));
        })

getAll() : Example :

     this.router.navigate(['example', { foo: ['bar', 'baz'] } ]);

     this.activatedRoute.paramMap.subscribe(params => {
          console.log(params.getAll('foo'));
        })