简体   繁体   中英

How can we use service just like a factory?

<!DOCTYPE html>
<html ng-app='myApp'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>
    var app = angular.module('myApp', []);
    app.controller('x', function (ser) {
        alert(ser.val);
    });
    app.service('ser', function () {
        var obj = {};
        obj.val = 'xyz';
        return obj;
    })
</script>

<body>

    <h1 ng-controller='x'>My First JavaScript Animation</h1>

</body>

</html>

We can create on object and give the object properties and return it in factories,but service is a constructor function,but here in the program i'm doing the same as i should do in factory by creating and returning an object. Isn't it should be done using this keyword...but it's working.how?

I referred this link: [ https://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make][1]

As per that link:

These names cause confusion for almost every AngularJS developer when starting out. They really shouldn't because they're syntactic sugar for (almost) the same thing! Here are their definitions from the AngularJS source:

function factory(name, factoryFn) { 
    return provider(name, { $get: factoryFn }); 
}

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
}

From the source you can see that service just calls the factory function which in turn calls the provider function.

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