简体   繁体   中英

AngularJS : How to get returned value from factory

I am very much new in AngularJS and I have the following problem:

View:

<div>
    <form role="form" name="loginForm" class="form-horizontal login-form">
        <div class="form-group">
            <p class="login-form-msg">Welcome : {{user.username}}</p>
            <label for="inputUserName" class="col-sm-2 control-label login-form-label">Base</label>
            <div class="col-sm-10">
                <input type="text" placeholder="Enter base" class="form-control" required ng-model="user.code">
            </div>
        </div>
        <div class="form-group">
            <label for="inputUserName" class="col-sm-2 control-label login-form-label">Username</label>
            <div class="col-sm-10">
                <input type="text" placeholder="Enter name" class="form-control" required ng-model="user.username">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword" class="col-sm-2 control-label login-form-label">Password</label>
            <div class="col-sm-10">
                <input type="password" placeholder="Password" id="inputPassword" class="form-control" required ng-model="user.password">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10 login-form-button">
                <button class="btn btn-default" type="submit" ng-disabled="loginForm.$invalid" ng-click="login(user)">Sign in</button>
            </div>
            <p class="login-form-msg">{{msgtxt}}</p>
        </div>
    </form>
</div>

Main js:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/login', {
        templateUrl: 'partials/login.html',
        controller:'loginCtrl'
    });
    $routeProvider.when('/welcome', {
        templateUrl: 'partials/welcome.html',
        controller:'loginCtrl'
    });
    $routeProvider.otherwise({ redirectTo: '/login' });
}]);

I have the following factory:

myApp.factory('getURLService', function ($http, config) {
    return {
        getURL: function (user,scope) {
            $http.get(config.backend + "/Device/GetURLbyCode", {
                params: { code: user.code }
            })
            .success(function (data) {
                var url = '';
                if (data.status == 'succ') {
                    url = data.Result;
                }
                else {
                    scope.msgtxt = data.msg;
                }
                return url;
            });
        }
    }
});

I need to use the returned value from this factory in other factories.

For example in my login factory:

myApp.factory('loginService', function ($http, $location, config) {
    return {
        login: function (user,url,scope) {

            $http.get(url + "/Device/Register", {
                params: { userName: user.username, password: user.password }
            })
            .success(function (data) {
                if (data.status == 'succ') {
                    $location.path('/welcome');
                }
                else {
                    scope.msgtxt = data.msg;
                }
            });
        }
    }
});

This is my controller:

myApp.controller('loginCtrl', function ($scope, getURLService, loginService) {
    $scope.msgtxt = '';

    $scope.login = function (user) {
        loginService.login(user,url,$scope); //call login service
    }
});

What do I need to do in my controller to actually return the url and then send it to the login service or any other service (or even controller) in the future?

Thanks in advance for your time and suggestion.

For returning data from the function you should return promise object which $http.get already returns it.

Additional thing which I wanted to point out is, passing $scope to the service disobey the rule of singleton, as you are creating a service which is dependent of the controller scope. Service should only accept the parameter and return the result by processing it, nothing else.

Code

return {
    getURL: function (user,scope) {
        return $http.get(config.backend + "/Device/GetURLbyCode", {
            params: { code: user.code }
        })
        .then(function (res) {
            var data = res.data;
            var url = '';
            if (data.status == 'succ') {
                url = data.Result;
            }
            else {
                scope.msgtxt = data.msg;
            }
            return url;
        });
    }
}

LoginService

myApp.factory('loginService', function ($http, $location, config) {
    return {
        login: function (user,url) {

            return $http.get(url + "/Device/Register", {
                params: { userName: user.username, password: user.password }
            })
            .then(function (response) {
                var data = response.data;
                if (data.status == 'succ') {
                    $location.path('/welcome');
                    return;
                }
                return data.msg;
            });
        }
    }
});

Controller

getURLService.getURL(user).then(function(url){
     //assuming you already having value of user available here
     loginService.login(user,url).then(function(message){ //call login service
         if(message)
            $scope.msgtxt = message;
     }); 
});

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