我正在嘗試修補我正在使用均值堆疊創建的專案中的任務。所有 api 的作業,但是當我嘗試使用 id 引數修補一個元素時,會出現一個錯誤:
"Object is possibly 'undefined'".
我想做的是:
- 獲取具有精確 id 的元素
- 使用該 id 作為查詢來修補該元素
這是代碼:
export class TaskServicesService {
constructor(private myHttp: HttpClient) { }
async updateTask(payload: any) : Promise<any> {
const task = await this.myHttp.get('http://localhost:3000/').toPromise();
const elId: any = task.id;
return await this.myHttp.patch('http://localhost:3000/list/', {title: payload}).toPromise();
}
}
uj5u.com熱心網友回復:
此錯誤的原因是方程的正確值(右值)可能是undefined。避免此錯誤的一種方法是在將物件undefined用作正確值之前檢查它是否存在。我知道在您的應用程式中,此錯誤是由task.id物件引起的。希望我們可以通過以下方式解決這個問題:
if(task.id !== null && task.id !== undefined)
{
const elId: task.id;
return await this.myHttp.patch('http://localhost:3000/list/', {title: payload}).toPromise();
}
else
{
/* Error Handling */
}
uj5u.com熱心網友回復:
嘗試使用可選鏈運算子 - ?:
const task: any = await this.myHttp.get('http://localhost:3000/').toPromise();
const elId: any = task?.id;
如果您確定task具有null或undefined以外的值,您還可以使用非空斷言運算子 - !:
const task: any = await this.myHttp.get('http://localhost:3000/').toPromise();
const elId: any = task!.id;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385504.html
標籤:javascript 有角的 打字稿 MongoDB 平均堆栈
