在范围

时间:2017-08-08 11:28:35

标签: javascript angularjs asynchronous promise q

我正在尝试实现一个控制器,其范围变量由服务变量设置,如下所示:

$scope.sidebar= resourceService.sidebar;

变量侧栏由启动时调用的函数设置:

var cb = function (api, data) {
    for (var key in data) {
        var logoArray = data[key];
        service.sidebar[key] = logoArray.map(function (logo) {
            logo.img = api + "/" + logo.img;
            return logo;
        });
    }
}
service.requestOnStartup = function (api) {
    var defer = $q.defer();
    $http.get(config.ApiEndpoint.Base + api).success(function (data) {
        if (angular.isObject(data)) {
            defer.resolve(cb(api, data));
        } else {
            $log.error("[ResourceService] Unexpected data from resource backend");
            defer.reject(data);
        }
    }).error(function (msg) {
        $log.error("Invalid request");
        defer.reject(msg);
    });
    return defer.promise;
};

当控件到达范围时,服务变量仍未解析,并且在解析时,对范围的控制将丢失。我如何使用承诺解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果直接显示$scope.sidebar,您的代码看起来很好。变量将以异步方式填充,以便稍后进行。

如果您在加载控制器时对其执行某些操作,则需要使用$watch

$scope.$watch('sidebar', function() {
  if ($scope.sidebar) {...} // check for existence here
});

顺便说一下,您可以像这样简化requestOnStartup

service.requestOnStartup = function (api) {
    return $http.get(config.ApiEndpoint.Base + api).then(function (data) {
        if (angular.isObject(data)) {
            return cb(api, data);
        } else {
            $log.error("[ResourceService] Unexpected data from resource backend");
            return $q.reject(data);
        }
    }, function (msg) {
        $log.error("Invalid request");
        return $q.reject(msg);
    });
};

答案 1 :(得分:0)

你也可以使用angular js的现有$ q服务:

service.requestOnStartup = function (api) {
    return $q(function(resolve, reject){
            $http.get(config.ApiEndpoint.Base + api).then(function (data) {
              if (angular.isObject(data)) {
                resolve(cb(api, data));
              } else {
                $log.error("[ResourceService] Unexpected data from resource backend");
                reject(data);
              }
            }, function (msg) {
                $log.error("Invalid request");
                reject(msg);
            });

    });
};