【发布时间】:2017-10-31 15:37:36
【问题描述】:
只是尝试从 http 结果设置我的组件属性,但没有成功。感谢您的帮助 ! (使用静态模拟对象)
类 - 对象
export class Gallery {
name: string;
}
服务
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);
}
}
组件
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调用结果
[{"name":"Cats"},{"name":"Dogs"}]
【问题讨论】:
标签: angular http typescript undefined