我想在component constructor 裡先load data,然後在ngOnInit() 裡面用這些data 來update 畫面。
可是我用了await-async 的方法去做好像不行,煩請高人指點.
這是我的component source code:
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);
});
}
}
這是我的service source code:
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();
}
}
I attached the screen dump for your reference.