我正在AngularJS中编写服务,我希望该服务在我选择的页面上进行重定向。我没有这个范围,所以我正在使用:
$window.location.assign('path');
我要问的是这是安全使用还是我应该使用不同的东西。
ps:那些不起作用:
$location.assign(); //assign is not a function
//
$location.path();
$scope.$apply(); //I don't have a $scope
非常感谢。
编辑:添加了代码(socketio.listen('auth.loggedInSuccessfully', function(data) {
我遇到了我描述的问题)
angular.module('frontendApp')
.factory('login', function ($window, socketio, $rootScope) {
// Service logic
// ...
var loginType = null;
// prepare socketio events
socketio.listen();
socketio.listen('auth.loggedInSuccessfully', function(data) {
console.log("Login verified by server!.. Redirecting...");
console.log("Login data received: " + JSON.stringify(data));
$rootScope.user = data.user;
$rootScope.$apply();
loginType = "facebook";
//console.log("$rootScope.user: " + JSON.stringify($rootScope.user.name));
//$location.path(destUrl); // THIS doesn't work.
$window.location.assign(data.destUrl); // this does!
});
socketio.listen('auth.loginFailed', function() {
console.log("Login failed!");
$rootScope.user = {}
});
socketio.listen('auth.logout', function() {
console.log("Logged out!");
$rootScope.user = {};
})
// Public API here
var api = {
fb: {
validateToken: function (access_token, destUrl) {
socketio.emit('fb.login', {
access_token: access_token,
destUrl: destUrl
});
console.log("Waiting server response...");
},[...]
};
return api;
});
答案 0 :(得分:1)
感谢发布您的代码。
我相信您的示例位置更改发生在AngularJS之外的事件处理程序中。通常,这需要将状态更改包装在$ scope中。$ apply。也许是这样的:
socketio.listen('auth.loggedInSuccessfully', function(data) {
console.log("Login verified by server!.. Redirecting...");
console.log("Login data received: " + JSON.stringify(data));
loginType = "facebook";
$rootScope.$apply(function() {
$rootScope.user = data.user;
$location.path(destUrl);
});
});