【问题标题】:Angular Http Promise return undefinedAngular Http Promise 返回未定义
【发布时间】: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


    【解决方案1】:

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

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

    见documentation:

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

    【讨论】:

    • 你成就了我的一天!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多