Angular HTTP承诺返回未定义



只是试图从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:gal是未定义的!!!!!

API调用结果

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

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

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

请参阅文档:

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

最新更新