How to get parameters from the Angular ActivatedRoute

非 Y 不嫁゛ 提交于 2021-02-07 10:50:56

问题


I'm trying to get the prameter :id from my activated route using observables. When I print params on the console I get the right values for :id. But it's not the case for this.id. I get the value NaN. Can you tell me what is the problem

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);
      }
    );
}
}

回答1:


Change to this.id = +params.get('id').

You should use the method get() because it returns a single value for the given parameter id. You were getting an error because params is not a key with id as a value.

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);     
  });
}



回答2:


I think the following code is going to work in your case:

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();
  })
);

}

Also you can try this:

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



回答3:


Retrieve the params like this:

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

} }




回答4:


The problem was in the route definition: putting : instead of ::



来源:https://stackoverflow.com/questions/55524175/how-to-get-parameters-from-the-angular-activatedroute

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