Search code examples
angularangular-promiseangular-httpclient

How to correctly handle this Angular promise to return an array of object?


I am very new in Angular and I am finding the following problem.

Into a service class I have this:

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 })
    }
}

So the getEvents() method perform a call toward an URL on my server by the get() method and convert this observable object into a promise by the **toPromise() method.

Then I converted the result of my response into a JSON object and I put the data field of this JSON into res.

Printing it into the console it is what I expect, this is the output:

(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)

Finnally I return it by this line:

.then(res => { return res })

Ok, in my Angular component I have to use this data and here I am finding some problem. I am trying to do it by this line:

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

But the IDE give me the following error message:

Type 'void' is not assignable to type 'any[]'.ts(2322)

Trying to compile I obtain a similar error:

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;});
                                                      ~~~~~~~~~~~

Why am I obtaining this error? What exactly mean? How can I try to fix it?

I think that my service method is returning a promise containing the JSON but probabily also this is wrong because my component class expects an array of object containing the JSON object. The array is declared in the component code in this way (and I can't change it because it is used by a PrimeNG calendar):

events: any[];

How can I try to fix this?


Solution

  • You didnt't return a value when you logged to the console. So the value from there on is void.

    You then are assigining this void value to an this.events. Apparently this should be an array of whatever ( any[] ). So that is what the message is telling you is wrong.

    // 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;
          })
    }