Angular 11- but data ['id'] is underlined in red in this section. How can I do this?

Viewed 56

I want to reach the id in the form and after adding, the details of the added record should be displayed.

  add(city:City)
  {

    this.httpClient.post(this.path+'cities/add',city).subscribe(data=>{
      this.alertifyService.success("Şehir Başarayla Eklendi.");
      this.router.navigateByUrl('cityDetail/'+data['id']);
    });
  }
2 Answers

Add response type to post function

add(city:City) {
  this.httpClient.post<{id: string>}(this.path+'cities/add',city).subscribe(data=>{
    this.alertifyService.success("Şehir Başarayla Eklendi.");
    this.router.navigateByUrl('cityDetail/'+data['id']);
  });
}

You are not using the full functionality of typescript here, and that's why you aren't able to reach the id property. Anytime you can, define the type of arguments, responses, invocations and returns.

In your specific case, you forgot to tell angular how will the response of this post be. In other words, what specific type of data will you receive. In order to do that, you can use the typescript type assertion, and do something like:

Of course, the properties and their type I added to the post are just examples.

this.httpClient.post<{
    prop1: string;
    prop2: boolean;
    id: number
}>(this.path + 'cities/add', city)
Related