【发布时间】:2019-09-18 14:22:17
【问题描述】:
我想在组件构造函数中从 Angular 服务加载数据,并使用这些数据在 ngOnInit() 函数中更新 UI。
我正在使用 async-await 功能来实现它。
很遗憾,它不起作用。
这是我的组件源代码:
import { Component, OnInit } from '@angular/core';
import {MonthlyCalendar} from './monthly-calendar';
import { MonthlyCalendarService } from './monthly-calendar.service';
import { resolve } from 'url';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
monthlyCalendar: MonthlyCalendar;
constructor(private monthlyCalendarService: MonthlyCalendarService) {
this.monthlyCalendar = null;
console.log('t0:' + new Date());
this._getData();
console.log('t2:' + new Date());
}
ngOnInit() {
console.log('t3:' + new Date());
console.log(this.monthlyCalendar);
}
async _getData() {
await this.monthlyCalendarService.getMonthlyCalendar(null, null)
.then((data: MonthlyCalendar) => {
console.log('t1:' + new Date());
this.monthlyCalendar = data;
})
.catch ((err: Error) => {
alert(err.stack);
});
}
}
这是我的服务源代码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { MonthlyCalendar } from './monthly-calendar';
import { resolve, reject } from 'q';
@Injectable({
providedIn: 'root'
})
export class MonthlyCalendarService {
constructor(private http: HttpClient) { }
getMonthlyCalendar(year: number, month: number): Promise<object> {
const params = new HttpParams();
if (year != null) {
params.set('year', year.toString());
}
if (month != null) {
params.set('month', month.toString());
}
return this.http.get('backend/getMonthlyCalendar.php', {params}).toPromise();
}
}
这是我的component.html
<table>
<theader></theader>
<tbody></tbody>
</table>
我附上了屏幕转储供您参考。
【问题讨论】:
-
你可以添加你的模板代码吗?
-
你的意思是component.html吗?
-
是的,你使用的代码
monthlyCalendar -
目前,我想确保this.monthlyCalendar在ngOnInit()之前不为空,所以component.html只是初始内容。
-
如果我说你不能阻止渲染怎么办。而是将数据检索移动到父组件并使用 ngIf 仅在数据已解析时才呈现组件。其他在此组件中使用 ngIf 并在数据加载时使用某种加载动画。将异步调用或计算量大的操作移出构造函数。
标签: angular async-await