0

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"}]

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You made my day ! Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.