将控制器功能绑定到 ui-router ui-href

Bind a controller function to a ui-router ui-href

我是 angular 的新手,所以我可能做错了什么。

我正在使用 ui-router 用于状态,links 和 passport 用于用户身份验证。我在创建新用户和登录时没有问题,但我想创建一个 link 以便用户可以注销。

有什么方法可以将我的控制器的功能绑定到 ui-href link? 例如:

州道

    .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(这不起作用,它没有绑定与 usersignout 绑定的控制器)

  <a ui-sref="usersignout" ng-click="signCtrl.logoutUser()">Close Session</a>

您可以简单地省略控制器中的函数声明

.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
                    });
                });
    }
])