首页 > 解决方案 > 如何正确处理这个 Angular 承诺以返回一个对象数组?

问题描述

我是 Angular 的新手,我发现了以下问题。

进入服务类我有这个:

import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http'

@Injectable()
export class EventService {
    constructor(private http: HttpClient) {}

    getEvents() {
        return this.http.get('assets/json_mock/calendarevents.json')
                    .toPromise()
                    .then(res => JSON.parse(JSON.stringify(res)).data)
                    .then(res => console.log(res))
                    .then(res => { return res })
    }
}

因此getEvents()方法通过get()方法对我的服务器上的 URL 执行调用,并通过 **toPromise() 方法将此可观察对象转换为 Promise。

然后我将响应的结果转换为 JSON 对象,并将这个 JSON 的数据字段放入res中。

将它打印到控制台中,这是我所期望的,这是输出:

(3) [{…}, {…}, {…}]
0: {id: 1, title: "All Day Event", start: "2017-02-01"}
1: {id: 2, title: "Long Event", start: "2017-02-07", end: "2017-02-10"}
2: {id: 3, title: "Repeating Event", start: "2017-02-09T16:00:00"}
length: 3
__proto__: Array(0)

最后我通过这一行返回它:

.then(res => { return res })

好的,在我的 Angular 组件中,我必须使用这些数据,在这里我发现了一些问题。我试图通过这一行来做到这一点:

this.eventService.getEvents().then(events => { this.events = events;});

但是 IDE 给了我以下错误信息:

类型 'void' 不可分配给类型 'any[]'.ts(2322)

试图编译我得到一个类似的错误:

ERROR in src/app/fullcalendar/fullcalendar.component.ts:22:52 - error TS2322: Type 'void' is not assignable to type 'any[]'.

22     this.eventService.getEvents().then(events => { this.events = events;});
                                                      ~~~~~~~~~~~

为什么我会收到此错误?究竟是什么意思?我该如何尝试修复它?

我认为我的服务方法正在返回一个包含 JSON 的承诺,但这也可能是错误的,因为我的组件类需要一个包含 JSON 对象的对象数组。数组以这种方式在组件代码中声明(我无法更改它,因为它被 PrimeNG 日历使用):

events: any[];

我该如何解决这个问题?

标签: angularangular-promiseangular-httpclient

解决方案


当您登录到控制台时,您没有返回值。所以从那里的价值是void

然后,您将此 void 值分配给this.events. 显然这应该是一个由任何 ( any[]) 组成的数组。所以这就是信息告诉你的错误。

// should assign a typescript return type to the method to detect the error earlier
getEvents(): Promise<any[]> { 
    return this.http.get('assets/json_mock/calendarevents.json')
      .toPromise()
      .then(res => JSON.parse(JSON.stringify(res)).data)
      .then(res => {
        console.log(res);
        // you returned no value here!
        return res;
      })
}

推荐阅读