在控制器中访问$rootSope时的 angualrJS 未定义或空引用

AngualrJS Undefined or Null Reference When Accessing $rootSope in Controller

本文关键字:未定义 angualrJS 引用 时的 rootSope 控制器 访问      更新时间:2023-09-26

AngularJS最新发布候选版本:

我正在将一个 javascript 对象 - 从模块的运行函数中调用 say stuff 到$rootScope中,我相信它应该阻止。 这是代码:

'use strict';
/* App Module */
var app = angular.module('MyApp', ['ngRoute', 'API'])
    .run(function ($rootScope, API) {
        $rootScope.stuff = null;
        // call the API
        API.getStuff()
            .success(function(data){
                $rootScope.stuff = data;
            })
            .error(function(data){
                $rootScope.stuff = null;
            });
    });

现在,当我尝试从控制器访问 $rootScope 的 stuff 属性时,我在内容上收到"未定义或空引用"错误。 代码如下所示:

'use strict';
app.controller('indexController',
    function ($scope, $rootScope, otherAPI) {
        var
            stuff = $rootScope.stuff;
        // call the other API
        otherAPI.getDifferentStuff(stuff.property)
            .success(function(data){
                    $scope.differentStuff = data;
            })
            .error(function(data){
                        // do some error handling stuff here
            });
    });

我知道运行函数中的 api 调用成功,并且它正在为$rootScope中的东西分配一个值。 任何人都可以在这里看到我的代码有什么明显的问题吗?

感谢您的任何帮助!

API.getStuff异步 API 调用(看起来像这样)。在这种情况下,您的控制器很可能在异步调用返回之前被初始化,因此 $rootScope.stuff 仍然等于 null。如果您等到调用成功,那么您将拥有您的数据。