【问题标题】:How to get parameters from the Angular ActivatedRoute如何从 Angular ActivatedRoute 获取参数
【发布时间】:2019-08-26 16:41:40
【问题描述】:

我正在尝试使用 observables 从我激活的路由中获取参数 :id。当我在控制台上打印参数时,我得到了正确的值:id。但 this.id 并非如此。我得到值 NaN。 你能告诉我是什么问题吗

export class RecipeEditComponent implements OnInit {
  id: number;
  editMode = false;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(
      (params: {id: string}) => {
        this.id = +params.id;
        console.log(this.id);
      }
    );
}
}

【问题讨论】:

  • 您能否将该代码作为代码块而不是图像放入您的问题中。
  • console.log(params.id) 会得到什么?
  • 未定义即使我在打印参数时得到了正确的对象:id = 1
  • 这条路线怎么称呼?你的浏览器地址栏是什么?
  • 路由是:{ path: '::id/edit', component: RecipeEditComponent} 浏览器中的链接是:localhost:4200/recipes/0/edit

标签: angular parameters routing


【解决方案1】:

问题出在路由定义中: 把 : 而不是 ::

【讨论】:

    【解决方案2】:

    像这样检索参数:

      ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        this.id = +params["id"];
        console.log(this.id);
      }
    );
    

    } }

    【讨论】:

    • 也许可以试试这个:Number(params["id"])
    【解决方案3】:

    更改为this.id = +params.get('id')

    您应该使用方法get(),因为它为给定的参数id 返回单个值。 您收到错误是因为 params 不是以 id 作为值的键。

    export class RecipeEditComponent implements OnInit {
      id: number;
      editMode = false;
    
      constructor(private route: ActivatedRoute) { }
    
      ngOnInit() {
      // paramMap replaces params in Angular v4+
       this.route.paramMap.subscribe(params: ParamMap => {
            this.id = +params.get('id');
            console.log(this.id);     
      });
    }
    

    【讨论】:

    • 它显示了这个错误:ERROR TypeError: "params.get is not a function"
    • 如果您使用的是 Angular v4+,请将 params 更改为 paramMap
    • 我已将其更改为 paramMap 但现在它不会在控制台上打印任何内容
    • 代码中有console.log(this.id)吗?
    • @Ellone + 号将 id 从字符串更改为数字。
    【解决方案4】:

    我认为以下代码适用于您的情况:

    ngOnInit() {
    this.heroes$ = this.route.paramMap.pipe(
      switchMap(params => {
        // (+) before `params.get()` turns the string into a number
        this.selectedId = +params.get('id');
        return this.service.getHeroes();
      })
    );
    

    }

    你也可以试试这个:

    this.sessionId = this.route
      .queryParamMap
      .pipe(map(params => params.get('id') || 'None'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2021-03-16
      • 2017-08-14
      • 2017-09-10
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多