2016-12-22 9 views
0

私は新しく角度を感じていますが、サービスをコントローラーの重いものにする方が良いと言われましたが、サービスを利用するのは難しいと感じています作成されました。私はこれについていくつかの質問を見てきましたが、私は解決策を見つけることができません。ここでコントローラーで角度サービスを使用する方法

は私のサービスは

(function() { 
    'use strict'; 

var office = angular.module('Office', []); 

office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) { 

    var auth = {} 

    auth.login = function (credentials) { 
     $http.post('/auth_api/login', credentials) 
      .then(function (data) { 
        $localForage.setItem('user', data.data) 
       }, 
       function() { 
        $scope.login_error = 'Invalid Username/password' 
       }) 
    } 

    $localForage.getItem('user').then(function (data) { 
     auth.isAuthenticated = !!data.id 
    }) 

    return auth 
}]) 

だとここで私のコントローラ

office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) { 

    $scope.login = auth.login($scope.user) 
}]) 
+0

あなたが直面している問題は何か? – Disha

+0

関数が 'return'ステートメントを省略すると、関数は' undefined'を呼び出し元に返します。関数型プログラミングのルールは - 常に何かを返す。 – georgeawg

答えて

0

私は...あなたのコードから簡単なバージョンを作成し、そのここで働いているのです。リンクをチェック - fiddle

app.factory('auth', ['$http', function ($http) { 
    var auth = {}; 
    auth.login = function (credentials) { 
     return "success"; 
    } 
    return auth; 
}]); 

あなたimplemenation

0

あなたのコードが正しいですが、あなたは、「認証」の工場から何かを返されていないとして、あなたはコントローラ内の任意の更新を取得されていませんとログイン機能を交換してください。以下のようにコードを変更して、工場出荷時のデータまたはログインを確認するメッセージを返します。

工場:

(function() { 
    'use strict'; 

    var office = angular.module('Office', []); 

    office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) { 

    var auth = {} 

    auth.login = function (credentials) { 
    return $http.post('/auth_api/login', credentials) 
     .then(function (data) { 
       $localForage.setItem('user', data.data); 
       setAuthentication(true); 
       return data.data; 
      }, 
      function (err) { 
       return err; 
      }); 
    } 

    auth.setAuthentication = function (isLoggedIn){ 
    this.isAuthenticated = isLoggedIn; 
    } 

    return auth; 
}]); 

コントローラー:

office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) { 
     $scope.login = function(){ 
     auth.login($scope.user).then(function (data){ 
     $scope.userDetails = data; 
     }, function (err){ 
     $scope.loginError = 'Invalid Username/password'; 
     }); 
     } 
}]); 
関連する問題