mario595
mario595

Reputation: 3761

Angular 2 route check if params contains valid value

I've got the following code in one angular2 component:

ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this.elementsService.getElement(+params['id']))
      .subscribe(element => {
                    this.elementToEdit = element;
                }
      );
  }

This component is being used in two cases, one where an id is provided in the url and one where there is no id provided. In the first case, it works fine. In the second, it works BUT there is a 404 error in the console: api/elements/NaN.

I am trying to fix that, but I couldn't find a way check if the id is in the url or not:

ngOnInit() {
  if(this.route.params['id']){<---doesn't work
    this.route.params
      .switchMap((params: Params) => this.elementsService.getElement(+params['id']))
      .subscribe(element => {
                    this.elementToEdit = element;
                }
      );
  }
}

Is there a way to do this and avoid calling the service if the id parameter is not present?

Upvotes: 1

Views: 4044

Answers (1)

Babar Hussain
Babar Hussain

Reputation: 2915

I'm using this in one of my project working fine for me

this.route.params.subscribe((params: any) => {
 if (params.id) {
  // Edit your element here
 } else {
  // Create your new element here
 }
});

and my route is this

{ path: "home/:id", component: HomeComponent },

Upvotes: 5

Related Questions