簡體   English   中英

如何訪問來自 API 響應的 ID,應該用作 deleteApp API 的參數傳遞

[英]How to access id which is coming from API response and should be used to pass as parameter for deleteApp API

文件

export class AppInfoComponent implements OnInit {   
data: [] = [];  
constructor(private getCmsService: GetCmsService, private router: Router, private deleteAppService: DeleteAppService) { }   
ngOnInit(): void {     
this.getcmsApps();   
}   
getcmsApps() {     
this.getCmsService.getApps().subscribe((res: any) => {       
this.data = res;       
console.log(res)       
console.log("res"+this.data)     
})   
} 
deleteApp(){         
this.deleteAppService.deleteAppById(this.data).subscribe((res: any) => {       
console.log(res)    
}) 
}

在 getcmsApps() function 中,第一個控制台語句返回 api 響應,但是當第二個控制台語句像這樣返回時

res[對象對象],[對象對象],[對象對象],[對象對象],[對象對象],[對象對象]

我需要在 deleteApp() function 內的 deleteAppById(APPID) 內傳遞應用程序 ID。

服務.ts文件

@Injectable({   providedIn: 'root' }) 
export class GetCmsService {   
constructor(private httpclient: HttpClient) { }   
getApps() {     
return this.httpclient.get(environment.url+ environment.cmsApp, {headers: {'Ocp-Apim-Subscription-Key':environment.OcpSubscriptionKey}
})   
}   
deleteAppById(appId: string) {     
return this.httpclient.delete(environment.url+ environment.cmsApp+appId, {headers: {'Ocp-Apim-Subscription-Key':environment.OcpSubscriptionKey}
})   
} 
}

這是回應在此處輸入圖像描述

So here i need to get respective App id to pass inside deleteAppById(appId: string) {} function for deleting apps.

看起來deleteAppId()一次只能接受一個id 因此,讓我們從this.data數組中獲取 object 的 id 並將其傳遞。

  getcmsApps() {
    this.getCmsService.getApps().subscribe((res: any) => {
      this.data = res;
      console.log(res);
      console.log('res' + this.data);
      for (let item of this.data) {
        if (item?.id) {
          this.deleteApp(item.id);
        }
      }
    });
  }

  deleteApp(id: string) {
    this.deleteAppService.deleteAppById(id).subscribe((res: any) => {
      console.log(res);
    });
  }

要在控制台中直接打印您的數據,請將此行console.log("res"+this.data)更改為console.log("res", this.data) - 這將正確打印您的數據。

其次,您的問題並不清楚,但是您可能正在使用 *ngFor 正確地在某種列表或表格中呈現“數據”? 正確的?

然后,假設您使用app作為 *ngFor 局部變量,在每個呈現的應用程序項目上您應該放置一個(click)處理程序,如下所示:

<ul>
 <li *ngFor="let app of data" (click)="deleteAppById(app.id)">{{app.name}}</li>
</ul>

.ts中,定義一個 function 用於刪除,如下所示:

deleteAppById(appId: string): void {
    this.deleteAppService.deleteAppById(appId)
       .subscribe((res: any) => {       
        console.log(res);
        //remove the deleted app item from the "data" array, or 
        //simply re-fetch it
}

這樣,當您單擊應用程序名稱時,將調用您的刪除 function。 但是,如果您之后不重新獲取“數據”數組,或者只是從數組中刪除該應用程序,該項目將保留在屏幕上。

我希望這個對你有用!

暫無
暫無

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

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