typescript Angular 4/5 - 路由 paramMap 与 params

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47809357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:07:01  来源:igfitidea点击:

Angular 4/5 - route paramMap vs params

angulartypescript

提问by Shota

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

我试图在我的 Angular 5 应用程序中获取 URL 参数,我找到了两种方法:

1) Using paramMap

1) 使用 paramMap

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

2) Using params

2) 使用 params

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

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

有什么区别吗?哪一个是最佳实践?

回答by

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 paramMapinstead.

两个较旧的属性仍然可用。它们的功能不如它们的替代品,不鼓励使用,并且可能会在未来的 Angular 版本中被弃用。

params— 包含特定于路由的必需和可选参数的 Observable。改用paramMap

Simple and efficient !

简单高效!

回答by Sajeetharan

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

实际上没有区别,但是params已经很旧了,可能很快就会被弃用

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.

一个 Observable,包含特定于路线的必需和可选参数的映射。该地图支持从同一参数检索单个和多个值。

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.

一个 Observable,其中包含可用于所有路由的查询参数的映射。该地图支持从查询参数中检索单个和多个值。

回答by M Abdullah

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

注:paramMap提供更多的便利与路线参数玩。有以下三种方法:

  1. has()
  2. get()
  3. getAll()
  1. 拥有()
  2. 得到()
  3. 得到所有()

has() :Example :

has() :示例:

    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 :

getAll() :示例:

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

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