当前位置: 动力学知识库 > 问答 > 编程问答 >

AngularJS $broadcast $on doesn't work at first time - intermittent issue

问题描述:

There is a strange behaviour in my AngularJS application. The use case it to create a user at "usercreate.html" and after successfully creating (over Backend REST- Service -> HTTP POST) a redirect to "usercreateresponse.html" is made.

I have two controllers:

  1. usercreate.html -> CreateUserController
  2. usercreateresponse.html -> CreateUserResponseController

and I share the data between CreateUserController and CreateUserResponseController over $rootScope.$broadcast and $rootScope.$on.

My problem now is, that when I have changed something in the code (AngularJS code) and I refresh the browser page and afterwards I will create a user, the user creation works fine and I am also redirected to usercreateresponse.html but no values are shown -> but this is only the first time -> if i navigate back to usercreate.html and create a user once again everything works fine.

I found out that in case if it is not working, a HTTP GET is made to get the HTML- Code from the back end. In case it works than only HTTP POST is made an everything works fine.

Does anybody know how to prevent the first user creation -> redirect problem?

Here the controller/services:

function CreateUserController($scope, CreateUserService) {

$scope.createUser = function(data) {

CreateUserService.createUser($scope.usernameCreate, $scope.passwordCreate, $scope.role);

}

}

services.factory('CreateUserService', function($rootScope, $location, $http) {

...

var res = $http.post('/users/createUser', dataObj);

res.success(function(data, status, headers, config) {

$rootScope.$broadcast('handleCreatedUser', {usernameCreate: data.username, passwordCreate: data.password, role: data.roles});

$location.path("usercreateresponse");

});

res.error(function(data, status, headers, config) {

...

});

}

return sharedCreateUserService;

});

function CreateUserResponseController($rootScope) {

$rootScope.$on('handleCreatedUser', function(event, args) {

$rootScope.usernameCreated = args.usernameCreate;

$rootScope.passwordCreated = args.passwordCreate;

$rootScope.role = args.role[0];

});

}

网友答案:

Instead of a broadcast, you can use a service which will store the response of the Creation of user. Then you can share it using the service with the CreateUserResponseController. With broadcast event, what might be happening is, you are broadcasting an event before the controller which handles it is instantiated. So, the $on may not have registered till then. And hence the issue you face.

分享给朋友:
您可能感兴趣的文章:
随机阅读: