简体   繁体   中英

How to use angular services with controllers

I'm new to angular and I've been told that it's better to make services do the heavy lifting for the controllers, but I'm finding it diffcult to make use of the services I've created. I've seen several questions on this but I can't find solutions.

Here's my service

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

And here's my controller

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

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

I have created a simpler version from your code.. and its working here . check the link - fiddle

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

replace login function with your implemenation

Your code is correct but as you are not returning anything from the "auth" factory, you are not getting any update in the controller. Change your code as shown below to return the data from factory or any message acknowledging the login.

Factory :

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

Controller :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM