【问题标题】:get Json with Typescript and Angular使用 Typescript 和 Angular 获取 Json
【发布时间】:2016-03-30 21:10:14
【问题描述】:

我有这个接口和这个类:

module AnimalPlanet{
     export interface Pet {
        Type: string;
        Name: string;
        Age: string;
        Color: string;
        SpecialCare: boolean;
        AvailableForAdoption: boolean;
        LDAdoption: boolean;
        History?: string;
        featured: boolean;
        newest: boolean;
        imageUrl: string;
        type: string;
        name: string;
    }

    export interface RootObject {
        pets: Pet[];
    }

  export class petsCtrl {
        dataFromServer : RootObject;
        constructor(private $http: ng.IHttpService) {
            this.$http.get('/app/pets/pets.json').then(function(response){
               console.log(response.data);
                   return response.data;

                });
        }
    }

    petsCtrl.$inject = ['$http'];
    app.controller("petsCtrl", petsCtrl);           
}

我尝试在视图中显示一些数据,但某些内容不适用于我的 get 方法。也许我的课程写错了。你能帮我吗?谢谢!

【问题讨论】:

    标签: angularjs json typescript


    【解决方案1】:

    确实,有问题。您必须将来自 http 调用的响应分配给范围的属性,而不是 return xxx。

    你的 Ctrl 必须是这样的:

     export class petsCtrl {
            dataFromServer : RootObject;
            constructor(private $http: ng.IHttpService, private $scope: any) {
                this.$http.get('/app/pets/pets.json').then(function(response){
                   console.log(response.data);
                       this.$scope.pets = response.data;
    
                    });
            }
        }
    
    petsCtrl.$inject = ['$http', '$scope'];

    然后在你的视图中,你可以显示属性pets:

    <div data-ng-bind="pets | json"></div>

    【讨论】:

    • 我收到了这样的json:[对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象] 0:对象年龄:“5-6 岁”AvailableForAdoption:真颜色:“棕色”历史:“被所有者遗弃" LDAdoption: true 名称: "Catty" SpecialCare: true 类型: "cat" 特色: true imageUrl: "img/photo_latest14.jpg" 最新: true proto: Object
    • 还有一个错误:TypeError: Cannot set property 'pets' of undefined
    • 对不起,你必须更改注入属性:petsCtrl.$inject = ['$http', '$scope'];(我更新代码)
    • 好的。目前没有错误,但在我看来什么也没发生。
      {{pet.Name}} {{pet.Type}} {{pet.Name}}
    • 能否在http回调中设置断点,检查是否有数据?也许一点 jsfiddle/plunkr 会有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2019-09-17
    • 1970-01-01
    • 2015-09-16
    • 2015-05-28
    相关资源
    最近更新 更多