angularjs - Angular - $scope 无法访问服务中的 $http 响应

标签 angularjs http service request

我有一个服务,我想通过 $http 获取数据(服务的原因是因为我需要在我的应用程序中多次进行此调用)

服务运行良好,这是代码:

factory('websiteService', function($rootScope, $http) {

    this.getWebsites = function(){
        http({
            method: 'GET',
            url: './data/websites.json'
        }).then(function successCallback(response) {
            return response.data;
        });
    }
    $rootScope.websiteService = this;
    return this;
});

然后,我在多个 Controller 中使用它,如下所示:

.controller('MyCtrl', function($scope, websiteService) {
    $scope.websites = websiteService.getWebsites(); // not working
});

不过,如您所料,这是行不通的。似乎 websites 是在 $http 请求结束之前定义的,但我可能错了。

我该如何解决这个问题?

最佳答案

服务的定义方式如下:

myModule.factory('websiteService', function($http) {

    function getWebsites() {
        return $http({
            method: 'GET',
            url: './data/websites.json'
        }).then(function successCallback(response) {
            return response.data;
        });
    }

    return {
        getWebsites: getWebsites
    };
});

下面是它应该如何使用:

myModule.controller('MyCtrl', function($scope, websiteService) {
    websiteService.getWebsites().then(function(webSites) {
        $scope.webSites = webSites;
    });
});

我建议你阅读 Traps, anti-patterns and tips about AngularJS promises了解您在 promise 方面所犯的错误。

关于angularjs - Angular - $scope 无法访问服务中的 $http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632578/

相关文章:

javascript - Angular Foundation 选项卡显示错误的内容和带有 ng-if 的事件选项卡

javascript - 跨源请求被阻止 : (Reason: CORS header 'Access-Control-Allow-Origin' missing)

spring - Grails可运行jar中的Spring Security重定向到HTTP

android - 从 Service 中停止 AlarmManager 但在 Activity 中创建

javascript - Angular 语法错误 : missing ; before statement

javascript - 停止重新定位光标

angularjs - 限制不工作

php - 是否可以在 PowerMTA 上阅读收到的电子邮件?

service - 运行 Windows 服务时登录失败

Grails 从服务中渲染 View ?