atomik
atomik

Reputation: 3

Angular Http Promise return undefined

Just trying to set my component property from a http result but no success. Thank for your help ! (working with a static mock object)

Class - Object

export class Gallery {
    name: string;
}

Service

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Gallery } from './GalleryModel';


@Injectable()
export class GalleryLoadService {

    private galleryUrl = 'api/Gallery/Get'; 

    constructor(private http: Http) {
    }


    getGalleries(): Promise<Gallery[]> {
        return this.http.get(this.galleryUrl)
            .toPromise()
            .then(response => response.json().data as Gallery[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); 
        return Promise.reject(error.message || error);
    }
}

Component

import { Component, OnInit } from '@angular/core';
import { Gallery } from './GalleryModel';
import { GalleryLoadService } from './gallery-services';


@Component({
    selector: 'my-gallery',
    templateUrl: 'gallery-component.html',
    moduleId: module.id 
})
export class GalleryComponent implements OnInit {
    galleries: Gallery[];

    constructor(private galleryService: GalleryLoadService) {
    }

    ngOnInit(): void {
        this.getGals();
    }

    getGals(): void {

        this.galleryService
            .getGalleries()
            .then(gals => {
            this.galleries = gals;
            console.log(this.galleries); <=== TypeError: gals is undefined!!!!!
            });
    }      
}

console.log return TypeError: gals is undefined!!!!!

API call result

[{"name":"Cats"},{"name":"Dogs"}]

Upvotes: 0

Views: 607

Answers (1)

Saravana
Saravana

Reputation: 40702

If that is the result you get from the API, then you should not be using response.json().data in your getGalleries method since there is no data property. Remove the data:

.then(response => response.json() as Gallery[])

See the documentation:

Make no assumptions about the server API. Not all servers return an object with a data property.

Upvotes: 2

Related Questions