簡體   English   中英

從Angular Factory調用JSON文件不起作用

[英]Calling JSON file from Angular Factory is not working

我是AngularJS的新手。 我試圖從工廠函數調用json文件,但它顯示我的var customers = []; 數組未更新。 請幫忙。

下面是我的代碼。

var demoApp = angular.module("myApp", []);

demoApp.factory('simpleFactory', ['$http', function($http){

    return {

        getCustomer: function(){
            var customers = [];
            return $http.get("http://www.w3schools.com/website/Customers_JSON.php")
            .success(
                function(data){

                    customers = data;
                },
                function(error){
                    console.log(error);
                });
            console.log(customers)
        }

    }

}]);

demoApp.controller("emplyCtrl", function($scope, simpleFactory){
    $scope.customers = simpleFactory.getCustomer();
});

演示小提琴

嘗試這樣的事情:

demoApp.factory('simpleFactory', ['$http', function($http){

    return {

        getCustomer: function(){

            return $http.get("json/customers.json").then(
                function(response){
                    var customers = [];
                    customers = response.data;
                },
                function(error){
                    console.log(error);
                });

        }

    }
}]);

在您的控制器中使用它:

demoApp.controller("emplyCtrl", function($scope, simpleFactory){
    simpleFactory.getCustomer().then(function(response){
        $scope.customers = response.data;
    });
});

由於視圖(HTML)從控制器的$scope讀取,因此您必須將數據放入$scope在控制器中的某個位置。 在工廠設置它僅允許從工廠內部訪問。

這是工作中的小提琴

希望這可以幫助!

您是否不認為應該在http前面加上“ $”符號? 我認為那里的“ $ http”應該表明它是可序列化的。 這就是為什么$ http應該在參數部分中以與前面的字符串語句中提到的方式相同的方式聲明。

另外,您不能只使用http,因為語法是在$前面使用$。 否則,angular dll將無法識別您的代碼。

demoApp.factory('simpleFactory',['$ http',function($ http){

var customers = [];

$http.get("json/customers.json")
    .success(function(data){
    customers = data;
});

var factory = {};

factory.getCustomer = function(){
    return customers;
};

return factory;

}]);

在這里看看示例: http : //www.w3schools.com/angular/angular_http.asp

謝謝,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM