0

我在阅读网页时进行了检查,然后使用结果通过 ng-repeat 刷新侧边栏,但出现错误:

未捕获的错误:未知的提供者:来自 myModule 的 $scope 或未捕获的错误:未知的提供者:来自 sharedService 的 $scope

我该如何解决?

这是我的代码

模块:

var myModule = angular.module('myModule', []); 

广播服务:

myModule.factory('mySharedService', function($rootScope) { //service
    var sharedService = {};

    sharedService.keyHistory = [];
    sharedService.linkHistory = [];
    sharedService.prepForBroadcast = function(key,link) {
        this.keyHistory = key;
        this.linkHistory = link;
        this.broadcastItem();
    };

    sharedService.prepForBroadcastAdd =function(key){
        console.log(this.keyHistory.push(key));
        //this.linkHistory = linkHistory+link;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

配置做检查:

myModule.config(function($scope,sharedService){

        $.ajax({
            url:"/fly/AJAX",
            type:"POST",
            contentType:'application/x-www-form-urlencoded; charset=UTF-8',     
            datatype:"json",
            success:function(data){
                if(data!=null){
                var loginResult = $.parseJSON(data);


                if (loginResult.success == true){ 
                    console.log("login success");
                    $("#userLable").html(loginResult.userName+'('+loginResult.loginID+')');//
                    if (loginResult.hasHistory==true) {  
                        sharedService.prepForBroadcast(loginResult.searchHistory,[]);
                        console.log("broadcast");
                    }
                    };
                }
            }
    });

});

侧键:

function SideCtrl($scope,sharedService) {
    $scope.$on('handleBroadcast', function() {

    $scope.keyHistory =sharedService.keyHistory;
    $scope.linkHistory = sharedService.linkHistory;
    });        

}

SideCtrl.$inject = ['$scope', 'mySharedService'];

谢谢 !

4

2 回答 2

1

该错误是由于尝试$scope在配置块中请求 a 而您无法做到的。如果我理解你想要做什么,那么我也认为你过于复杂了。我会以不同的方式解决问题。详细信息将取决于您的要求和用例,但基于您提供的信息......

我有一个服务负责与服务器通信并存储状态:

app.factory( 'loginService', function ( $http ) {
  var result;

  function doRequest( data ) {
    // just flesh out this post request to suit your needs...
    return $http.post( '/fly/ajax', data, {} )
    .then( function ( response ) {
      // assuming you don't care about the headers, etc.
      return response.data;
    });
  }

  // Do it once initially
  if ( ! angular.isDefined( result ) ) {
    result = doRequest();
  }

  // return the service's public API
  return {
    getStatus: function () { return result; },
    login: doRequest
  };
});

现在第一次请求此服务时,将$http发出请求。isDefined如果您从多个控制器访问它,则由于该语句,该帖子只会发生一次。然后,您可以在控制器中使用它:

app.controller( 'MainCtrl', function( $scope, loginService ) {
  loginService.getStatus().then( function ( data ) {
    // do whatever you need to with your data. 
    // it is only guaranteed to exist as of now, because $http returns a promise
  });
});

每个控制器都以相同的方式访问它,但它仍然只被调用一次!如果需要,您可以针对范围设置值并从视图中访问它:

app.controller( 'MainCtrl', function( $scope, loginService ) {
  loginService.getStatus().then( function ( data ) {
    $scope.loginId = data.loginID;
  });
});

在您看来:

<h1>Welcome, {{loginId || 'guest'}}!</h1>

如果需要,可以再次调用该函数:

app.controller( 'MainCtrl', function( $scope, loginService ) {
  // ...
  loginService.login( $scope.user ).then( function ( data ) {
    $scope.loginId = data.loginID;
  });
  // ...
});

如您所见,广播事件是完全没有必要的。

于 2013-02-19T07:48:41.667 回答
0

我会做不同的事情。我会创建某种更顶级的控制器,例如function MainController($rootScope, $scope, sharedService)并将其与 body: 连接起来<body ng-controller='mainController' ng-init='init()'。之后,您应该init()MainController.

在这个初始化方法中,我会调用sharedService它应该发出 AJAX 请求(通过$http!这是最佳实践,它与 jQuery 非常相似)并在需要时广播适当的事件。

这样,您确保只调用一次初始化(何时MainController初始化),您坚持使用 Angular 的最佳实践并避免看起来不可靠的代码。

于 2013-02-19T06:49:03.207 回答