陪伴而非守候
2021-12-02 15:32:10
我有一個 TypeScript 類,我在其中調用了一個調用后端 api 的方法,以從服務器獲取數據以放入網格中。目前我有硬編碼的列和行只是為了測試我將如何做到這一點。當我按照下面的示例放置列和行設置代碼時,我會正確填充網格。export class FooComponent { private columnDefs = []; private rowData = []; private gridOptions: GridOptions; private data: any; constructor(private http:HttpClient ) { this.getFoo();this.gridOptions = <GridOptions>{}; this.gridOptions.columnDefs = [ {headerName: 'Make', field: 'make' }, {headerName: 'Model', field: 'model' }, {headerName: 'Price', field: 'price'} ]; this.gridOptions.rowData = [ { make: 'Toyota', model: 'Celica', price: 35000 }, { make: 'Ford', model: 'Mondeo', price: 32000 }, { make: 'Porsche', model: 'Boxter', price: 72000 } ]; } getFoo(){ this.http.get(`https://xxx`).subscribe(response => { this.data = response; }, error => { console.log(error); }); }但是當我將列和行設置代碼放在我想要的 getFoo 方法中時,我的網格數據沒有設置,我得到了一個加載框。export class FooComponent { private columnDefs = []; private rowData = []; private gridOptions: GridOptions; private data: any; constructor(private http:HttpClient ) { this.getFoo(); } getFoo(){ this.http.get(`https://xxx`).subscribe(response => { this.data = response; }, error => { console.log(error); }); }我試圖通過從 getFoo 返回一個承諾,然后在承諾的“then”中設置列和行數據來解決這個問題,但得到了相同的加載框。這是我的標記。<ag-grid-angular style="width: 700px; height: 500px;" class="ag-theme-balham" [gridOptions]="gridOptions" ></ag-grid-angular>有任何想法嗎?
1 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
你可以這樣做:
export class FooComponent {
private columnDefs = [];
private rowData = [];
private gridOptions$: Observable<GridOptions>;
constructor(private http:HttpClient ) {
}
ngOnInit() { this.getFoo(); } // call it here, not in constructor
getFoo(){
this.gridOptions$ = this.http.get(`https://xxx`);
}
您可以通過對其執行 .map 并執行您的業務邏輯來轉換 http 請求,并且該響應將是可觀察的。
之后就在 html 中這樣調用它:
<ag-grid-angular
style="width: 700px; height: 500px;"
class="ag-theme-balham"
[gridOptions]="gridOptions$ | async"
>
這將異步更新模型并為您觸發更改檢測。
添加回答
舉報
0/150
提交
取消