簡體   English   中英

在 angular 中獲取編輯功能的 Id

[英]To get Id for edit functionality in angular

我在待辦事項應用程序中創建了一個用於編輯功能的彈出窗口,為此我需要獲取任務的 ID。 使用路線沒有給出正確的結果。 還有其他方法可以實現嗎? 我已經給出了下面的代碼。

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

確認您在編輯組件的路徑中具有相同的 ID:

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

在組件中使用它

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

或使用:

  ngOnInit(){

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

   }

使用 Angular 文檔: https://angular.io/tutorial/toh-pt5#extract-the-id-route-parameter

您需要使用ActivatedRoute才能從 URL 獲取 id,請按照以下步驟使用它。

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

我希望這能回答你的問題,如果我有什么不對,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM