首页 > 解决方案 > 将谷歌日历数据从服务传递到组件

问题描述

数组未从服务传递到组件:

在页面上的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>

标签: arraysangulartypescriptgoogle-calendar-apigoogle-api-js-client

解决方案


那是因为您以不正确的方式混合了 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 的更多信息


推荐阅读