我是棱角分明的,所以也许我做错了。
我正在使用ui-router作为用户身份验证的状态和链接以及通行证。我创建新用户并登录时没有问题,但我想创建一个链接,以便用户可以注销。
有没有办法将函数从我的控制器绑定到ui-href链接? 例如:
州路线
.state('usersignout', {
url: '/users/signout',
templateUrl: '/views/users/usuarios-signout.html',
controller: 'UsersSignController',
controllerAs: 'signCtrl'
});
控制器
.controller('UsersSignController', ['$http', '$state', 'Authentication',
function($http, $state, Authentication) {
this.logoutUser = function() {
$http({
// call my endpoint to do a passport's logout
method: "GET",
url: "/api/users/signout"
})
.then((response) => {
//successCallback
Authentication.setUser(null);
$state.go('home');
},
(response) => {
//errorCallback
$state.go('error', {
errorDetails: response
});
});
};
}
])
HTML (这不起作用,它不绑定与userignout绑定的控制器)
<a ui-sref="usersignout" ng-click="signCtrl.logoutUser()">Close Session</a>
答案 0 :(得分:0)
您可以简单地省略控制器中的函数声明
.controller('UsersSignController', ['$http', '$state', 'Authentication',
function ($http, $state, Authentication) {
$http({
// call my endpoint to do a passport's logout
method: "GET",
url: "/api/users/signout"
}).then((response) => {
//successCallback
Authentication.setUser(null);
$state.go('home');
},
(response) => {
//errorCallback
$state.go('error', {
errorDetails: response
});
});
}
]);
初始化控制器实例后,将立即调用注销请求。您还应该将http呼叫转移到某个服务,即
.service('SomeService', function ($http, Authentication) {
this.logout = function () {
return $http.get("/api/users/signout")
.then(() => {
Authentication.setUser(null);
})
}
})
在这种情况下,控制器应如下所示:
.controller('UsersSignController', ['$state', 'SomeService',
function ($state, SomeService) {
SomeService.logout
.then(() => {
$state.go('home');
},
(response) => {
//errorCallback
$state.go('error', {
errorDetails: response
});
});
}
])