Struggling to update my component property with an HTTP result, but encountering issues. Thank you for your assistance! (currently using 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.fetchGalleries();
}
fetchGalleries(): void {
this.galleryService
.getGalleries()
.then(galleries => {
this.galleries = galleries;
console.log(this.galleries); <=== TypeError: galleries is undefined!!!!!
});
}
}
console.log return TypeError: galleries is undefined!!!!!
API call result
[{"name":"Cats"},{"name":"Dogs"}]