arrays - 将谷歌日历数据从服务传递到组件
问题描述
数组未从服务传递到组件:
在页面上的test()
函数中service.ts
,谷歌日历数据被成功读取并推送到一个名为response
. 所有数据日志。
lesson-summary.component.ts
调用test()
函数时,数组response
数据不显示在lesson-summary.component.html
谢谢你的帮助!
谷歌日历.service.ts
import { Injectable, Directive } from "@angular/core";
import * as moment from "moment-timezone";
declare var gapi: any;
@Injectable({
providedIn: "root"
})
export class GoogleCalendarService {
private response = [];
constructor() { }
test() {
gapi.load("client", () => {
gapi.client.init({
apiKey: "API string here",
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
}).then(() => {
var month = moment().month();
const firstOfMonth = moment().startOf("month").format("YYYY-MM-DD hh:mm");
const lastOfMonth = moment().endOf("month").format("YYYY-MM-DD hh:mm");
var firstOfMonthUTC = moment.tz(firstOfMonth, "America/Toronto").format();
var lastOfMonthUTC = moment.tz(lastOfMonth, "America/Toronto").format();
return gapi.client.calendar.events.list({
calendarId: "calendar id here",
timeMax: lastOfMonthUTC,
timeMin: firstOfMonthUTC,
singleEvents: true
});
})//end of .then
.then((data) => {
this.response.push.apply(this.response, data.result.items);
console.log(data.result.items, "data.result.items");
return this.response;
});//end of .then
});//end of .load
}//end of test
}//end of export
课程摘要.component.ts
import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs";
import { GoogleCalendarService } from "../google-calendar.service";
declare var gapi: any;
@Component({
selector: "app-lesson-summary",
templateUrl: "./lesson-summary.component.html",
styleUrls: ["./lesson-summary.component.css"]
})
export class LessonSummaryComponent implements OnInit {
private response;
constructor(
private calendarService: GoogleCalendarService) {
this.response = this.calendarService.test();
}
ngOnInit() {
}
}
课程摘要.component.html
<ul>
<li *ngFor = "let item of response">
{{ item.summary }}
</li>
</ul>
解决方案
那是因为您以不正确的方式混合了 Promise 和同步函数,因此该test()
函数不会返回任何内容。
尝试向您的test()
:
test() {
return new Promise(resolve => { // <-- now test func return promise
gapi.load("client", () => {
gapi.client.init({
apiKey: "API string here",
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
}).then(() => {
// code...
}).then((data) => {
// code...
resolve(this.response); // <-- when we have the response, we are resolving the promise
});
});
});
}
然后在组件中使用这个promise:
this.calendarService.test().then(data => this.response = data);
在 MDN 上了解有关 Promise 的更多信息
推荐阅读
- dataframe - 使用新的“其他变量”创建新列
- c# - IIS 没有收到对 HTML 的更新?
- python - Pandas 将每年与某个属性关联的列合并为单独的列
- javascript - 有没有办法使用 Web Audio API 重新采样音频流?
- python - 在 Plotly 中使用三个 1D 浮点数组创建 3D 曲面图
- javascript - 是什么导致 React.js 上的表单解析错误
- reactjs - 创建反应应用程序 - 小型 EC2 服务器上的 `yarn build` 占用 100% CPU 并使其无响应
- c++ - 树形图的直径
- python - 从经度和纬度获取国家名称
- amazon-web-services - 将事件数据从 Amazon EventBridge 传递到 AWS Fargate 任务