繁体   English   中英

如何将 Angular JS 服务中的变量设置为来自 AngularJS 服务中 $http 调用的响应数据?

[英]How do I set a variable within an Angular JS service to the response data from an $http call within an AngularJS service?

我有以下服务,我最终想要缓存。 但是,我似乎无法弄清楚如何在 Angular 中使用 $http 将服务中的变量设置为来自 REST 调用的响应数据。

routerApp.service('activityService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];

    this.temp = null;

    this.setTemp(x) {
        this.temp = x;
    }

    this.getActivities = function(x) {

        var promise = $http({
            method: 'GET',
            url: 'my url is here...'
        }).then(function(response) {
            //setTemp(response.data); //definitely wont work
            return response.data;
        });

        //how to set temp to response.data???
       setTemp(promise.data); //doesn't work - 
    };
});

我不太了解 JS(或角度)。 做这个的最好方式是什么?

不需要缓存 angular 服务,它保证是一个单例。
如果您打算缓存响应数据,您将在您的服务中创建一个缓存对象。

现在关于主要问题。 在这段代码中,误用了承诺而不是角度服务。 Promise 是异步的,这意味着提供给.then()的回调将在一段时间后执行,当请求完成时。 除了.then返回另一个承诺,您应该从activityService.getActivities方法返回。

this.getActivities = function(x) {
    var promise = $http({
        method: 'GET',
        url: 'my url is here...'
    }).then(function(response) {
        setTemp(response.data); //meaning that setTemp somehow modifies it's argument
        return response.data;
    });
    return promise;
};

然后在您的控制器之一中,您将使用此服务的方法将.then附加到它的返回值。

.controller('someController', function (activityService) {
        activityService.getActivities()
            .then(function (data) {
                    doSomethingWithResponse(data);
                }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM