无法通过在线 JSON 文件在工厂中提取数据

not able to pull data in factory by online json files

本文关键字:工厂 提取 数据 文件 JSON 在线      更新时间:2023-09-26

我创建了一个名为 service 的工厂.js

myAppServices=angular.module('myAppServices',['ngResource']);
myAppServices.factory('ProfileData',['$resource', function($resource){
    return $resource('http://www.w3schools.com/json/myTutorials.txt', {}, {
        query: {method: 'GET', isArray: false}
    });
}]);

我的控制器是:

myAppControllers.controller('ProfileListCtrl',['$scope', 'ProfileData', '$timeout', function($scope, ProfileData, $timeout) {
    var promise = ProfileData.query();
    promise.$promise.then(function(response) {
        $scope.data= response;
        console.log($scope.data);
});    
    }]);

由于无法获取数据,我在这里没有得到任何控制台。请在这里帮助我。

  • 注意

如果我使用保存的文件地址而不是 json 文件的在线 url,那么它可以工作

控制器.js

(function () {
    angular
            .module('app')
            .controller('ProfileListCtrl', ProfileListCtrl);
    ProfileListCtrl.$inject = ['$scope', 'ProfileDataFactory'];
    function ProfileListCtrl($scope, ProfileDataFactory) {
        $scope.data = [];
        function init() {
            ProfileDataFactory.get().then(function (response) {
                angular.copy(response, $scope.data);
                console.log(response);
            });
        }
        init();
    }
}());

工厂.js

(function () {
    angular
            .module('app')
            .factory('ProfileDataFactory', ProfileDataFactory);
    ProfileDataFactory.$inject = ['$http'];
    function ProfileDataFactory($http) {
        var self = this;
        self.get = $http.get('http://www.w3schools.com/json/myTutorials.txt').then(function (response) {
            return response.data;
        });
        return self;
    }
}());