在angularJS中$ broadcast vs. $ stateProvider

时间:2017-11-13 05:58:07

标签: angularjs state broadcast

我将约5 $ http .get和.post方法的响应从控制器传递给其他控制器。我计划使用广播来传递这些回复。然而,似乎state.go可能是更好的路线。 (没有双关语:)。我已经定义了几个状态,我应该简单地添加其他非url切换状态来传递这些参数吗? 谢谢

1 个答案:

答案 0 :(得分:2)

I would say that you should use Resolves in Angular Routes

//Example 
$routeProvider
    .when("/chat", {
        templateUrl: "msgView.html",
        controller: "msgController",
        resolve: {
            messages: function($http){
                //return your $http.get calls data
        }
    }
});

//use resolve like this in controller
app.controller("msgController", function (messages) {
    $scope.messages = messages;
});

You could also make this state an abstract or do the resolve work in your top most parent state or in the immediate parent state.

Example using ui-router

$stateProvider
  .state('chat', {
    url: '/chat',
    templateUrl: 'partials/chat.html',
    controller: 'msgController as vm',
    resolve: {
      messages: function($http){
                //return your $http.get calls data
        }
    }
  });

By doing this you will ensure that your data is available before you init your view and controller. If your data is empty or partial then you can handle that according to the way you want in your controller like show "No data available" message or something.

This also ensures that if any error occurs in your resolve then the user will be redirected to the 404 page or any other page you specify in

$state.defaultErrorHandler((error: any) => {
                $state.transitionTo("404");
            });