Home > other >  To get Id for edit functionality in angular
To get Id for edit functionality in angular

Time:11-23

I have created a popup for edit functionality in my todo app and I need to get the id of the task for the purpose. using route is not giving a correct result. Is there any other way I can achieve it? I have given the code below.

this.id = this.route.snapshot.params['id'];

  console.log(this.formData.value);
  this.todoService.editTasks(this.id, this.formData.value).subscribe((res: any)=>{
    console.log('update successful');
    // this.router.navigateByUrl('/tasks');
  })
  
}```

CodePudding user response:

verfiy that you have the same id in the path of edit component :

{path: "edit/:id", component: someComponent}

use that in the component

 import { ActivatedRoute } from '@angular/router';
    constructor(private route: ActivatedRoute) {}

        ngOnInit(){
    //you need to unsubscribe in the ngOnDestroy 
      this.subscription =   this.route.paramMap.subscribe(params=> {
               //i use   to convert the id to a number type
                let id = params.get('id');
            }
      //To prevent memory leak
      ngOnDestroy(): void {
        if (this.subscription)
          this.subscription.unsubscribe()
      }

or use that :

  ngOnInit(){

let id =this.route.snapshot.paramMap.get('id');

   }

use the Angular doc : https://angular.io/tutorial/toh-pt5#extract-the-id-route-parameter

CodePudding user response:

You need to use ActivatedRoute in order to get the id from the URL, check the following steps to use it.

// import
import { ActivatedRoute } from '@angular/router';

//dependency injection
 constructor(private route: ActivatedRoute) { }

//implementation
  ngOnInit() {
    this.route.paramMap.subscribe(
      params => {
        this.id= params.get('id'); // This is the required Id
      })
  }

I hope this answers your question, Let me know if I got something wrong.

  • Related