Angular Http Promise返回undefined

时间:2017-05-31 02:02:34

标签: angular http typescript undefined

只是尝试从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返回TypeError:gals未定义!!!!!

API调用结果

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

1 个答案:

答案 0 :(得分:2)

如果这是您从API获得的结果,那么您不应该在response.json().data方法中使用getGalleries,因为没有data属性。删除data

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

请参阅documentation

  

不要假设服务器API。并非所有服务器都返回   具有data属性的对象。