ERROR Error: The requested path contains undefined segment at index 1

Viewed 3849

I am trying to create a onClick function, such that when a button is clicked it navigates to another page with the id of the selected function. However whenever i run the following code i get in console:

ERROR Error: The requested path contains undefined segment at index 1

component.ts:

constructor(private damageAssessmentService: DamageAssessmentReportService, private router: Router, private route: ActivatedRoute) {}

    oneDAFormID: string;
      onView(){
        this.damageAssessmentService.getOneDAForm(this.oneDAFormID)
        this.route.params.subscribe((params: Params)=> {
          this.oneDAFormID = params['getDAId'];
          console.log(this.oneDAFormID);
        //navigate to /view-full-daform/_id
        this.router.navigate(['/view-full-daform' , this.oneDAFormID])
      })
      }

Service:

getOneDAForm(getDAId: any){
    return this.webReqService.get(`DamageAssessmentForm/${getDAId}`);
  }

Webservice:

get(uri: string) {
    return this.http.get(`${this.ROOT_URL}/${uri}`)

I don't quite know how to get the id from the page and navigate to the other page so i can implement the id in the ngOnInit(). Any assistance would be appreciate

3 Answers

you can also try using routerLink within the html to route with the id, so in your case, on a button tag:

<button [routerLink]="['/view-full-daform', id]">Next</button>

however you will need to store you path to the view-full-daform as

path: 'view-full-daform/:id'

It tells you at index 1 which is a big clue.

Here is an example of how you're using the router's navigate function:

this.router.navigate([x, y]) // Where x, y are route segments

This function takes multiple params and joins the indexes in the end, but it can't join anything that's undefined or null.

In your case, since we start counting at 0, index 1 would be the second param.

So that index is either

  1. Not defined
  2. You are getting your router params incorrectly
  3. You are not getting your route params at all (null).

That's what this error is telling you.

First, you need to declare a route to math with your route

{ path: 'hero/:id', component: HeroDetailComponent }

Subsequent use the router on the click event In your component, get the id passing the id to the method.

this.router.navigate(['/heroes', 5])

In the destination, the component import ActivatedRoute from the router package and add private variables to the constructor so that Angular injects them (makes them visible to the component).

constructor(
  private route: ActivatedRoute,
) {
 const id = this.route.snapshot.paramMap.get('id')!;
}

You can read a complete example in official angular documentation https://angular.io/guide/router#heroes-list-optionally-selecting-a-hero

Related