How can I gain access to a Javascript variable from within a return function?

☆樱花仙子☆ 提交于 2019-12-11 13:24:36

问题


    function storyData($http, $q) {
        var URL = 'stories.json';

        var storyCache = [];

        this.getStories = function() {
            var deferred = $q.defer();

            alert(URL);

            $http({method: 'GET', url: URL})
                .success(function (data, status, headers, config) {
                    storyCache = data;
                    alert(storyCache); //correct data appears in the alert window, but this doesn't set the instance storyCache variable for some reason

                    deferred.resolve(data);
                })
                .error(function (data, status, headers, config) {
                    deferred.reject(status);
                });

            return deferred.promise;
        };

        this.stories = function() {
            return storyCache;
        }
    }

My app -

'use strict';

var angularApp = angular.module('ccsApp', ['ngRoute', 'ngAnimate', 'ui.bootstrap']);

angularApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'stories.html',
                controller: 'StoryController as StoryCtrl',
                resolve: {
                    stories: function(storyData) {
                        return storyData.getStories();
                    }
                }

            })
            .otherwise({
                redirectTo: '/'
            });
    }
]);

Within my controller, I'm not injecting the "stories" value from the routeProvider so that I can use my service.

Why am I unable to change storyCache from within my $http method? I'm confident this is something terribly simple, but my research hasn't led me to an answer. Thank you in advance for your help.

The async. aspect of this works fine and is not the problem. I'm ensuring that I have the data by using the resolve object on my routeProvider. Also, I'm ensuring that I have the data before the deferred.resolve(data) method executes by issuing an alert on it. I don't have the solution, but an error in my use of async. is not the solution either.

来源:https://stackoverflow.com/questions/27831945/how-can-i-gain-access-to-a-javascript-variable-from-within-a-return-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!