2016-05-12 3 views
0

私は角度がついていないので多分間違っています。コントローラー機能をui-router ui-hrefにバインドする

私は状態とリンクには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

(これは、それがusersignoutに縛らコントローラを拘束するものではないですが、機能していません)
<a ui-sref="usersignout" ng-click="signCtrl.logoutUser()">Close Session</a> 

答えて

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

ログアウト要求はコントローラのインスタンスが初期化された直後に呼び出されるコントローラで関数宣言を省略することができます。

.controller('UsersSignController', ['$state', 'SomeService', 
    function ($state, SomeService) { 
     SomeService.logout 
      .then(() => { 
        $state.go('home'); 
       }, 
       (response) => { 
        //errorCallback 
        $state.go('error', { 
         errorDetails: response 
        }); 
       }); 
    } 
]) 
+0

はい、私は認証サービスへのHTTP呼び出しを移動することができますが、私の問題があることです:あなたはまた、動きのhttpのように見えるべきであるすなわち

.service('SomeService', function ($http, Authentication) { this.logout = function() { return $http.get("/api/users/signout") .then(() => { Authentication.setUser(null); }) } }) 

その場合、コントローラには、いくつかのサービスを呼び出す必要があります私はコントローラの関数を呼び出す方法を知らない。とにかくありがとう:) – RufusSC2

+0

私の最初の例を見てくださいthis.logoutUser = function(){宣言を削除しました。その場合、ログアウトロジックは 'usersignout'状態を入力した後に呼び出され、htmlから 'ng-click = "signCtrl.logoutUser()"を削除できます。このリンクからコントローラ機能を呼び出すことはできません。なぜなら、このリンクをクリックすると、あなたは「usersignout」状態ではないからです。 –

+0

ああ、私はそれを後で試してみるよ、ありがとう – RufusSC2

関連する問題