有多個模塊(例如職業、部門等),我通過存盤程序(選擇查詢)從 SQL 服務器接收資料,進入后端 NEST JS,然后進入 Angular 前端以顯示這些模塊(職業、部門等),但問題是當我單擊按鈕時沒有任何反應,當我第二次單擊按鈕時,資料會顯示在網頁上。當我在 Postman 中檢查時,后端作業正常,第一次收到資料。問題出在前端。
Angular Service.ts 代碼:
getdepartments(){
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer' ' ' GlobalService.authtoken);
return this.http.post<any>('http://localhost:3000/employee/getdepartments/',null,{headers}).subscribe(({data}) => {
this.dataout = data});
}
組件.ts 代碼:
departments(){
this.departmentsService.getdepartments();
this.dataout=this.departmentsService.dataout;
}
HTML 代碼:
<div>
<tr>
<th>Departments </th>
<th>Description </th>
</tr>
<tr *ngFor="let index of dataout">
<td>{{index.Department}}</td>
<td>{{index.Description}}</td>
</tr>
</div>
網頁:

uj5u.com熱心網友回復:
問題是當您為組件設定資料時,對后端的異步呼叫尚未完成:
departments(){
// this starts the call to your backend
this.departmentsService.getdepartments();
/* you immediately set "dataout" to datatout of your service,
but at this point your backend call has not finished so dataout
in your service is not set yet
*/
this.dataout=this.departmentsService.dataout;
}
例如,您可以通過將http.post呼叫后端的 observable 暴露給組件來解決這個問題(順便說一句,這應該是一個 get 呼叫,原因很明顯):
getdepartments(){
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer' ' ' GlobalService.authtoken);
return this.http.post<any>('http://localhost:3000/employee/getdepartments/',null,{headers});
}
并在您的組件中訂閱該 observable:
departments(){
this.departmentsService.getdepartments().subscribe( data => this.dataout = data);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467697.html
標籤:有角度的
上一篇:如何知道導航是否取消?
下一篇:如何使用指令訂閱組件的某些事件
