Angular Service Definition: service or factory

前端 未结 1 1735
青春惊慌失措
青春惊慌失措 2020-12-06 19:57

I am an angular newbie, I am building an application, one thing really puzzling me is there are couple of ways of defining a service, and I read more from this link: How to

相关标签:
1条回答
  • 2020-12-06 20:16

    you have two big problems there:

    • the factory returns an object with incorrect syntax.
    • javascript scope of variables is functional

    That is, You should be returning an object like {key: value, key: value}

    values can be functions. however, you return {key = value, key = value}

    First fix:

    return { 
        getSomething : function() {...},
        getData : function... 
    }
    

    Secondly, not being able to call functions is normal. See this jsfiddle. I mocked everything. You can call one of the functions returned by the service. However, when from getSomething try to call getData, you get "undefined":

    app.factory('testSO', function () {
    return {
        getSomething: function () {
            console.log('return getsomething');
            getData();
        },
    
        getData: function () {
            console.log('return getData');
        }...
    

    This would be the same as declaring everything in the scope of the factory function and return references see in jsfiddle:

    app.factory('testSO', function () {
        var getSomething = function () {
            console.log('return getsomething');
        };
        ...
    return {
        getSomething: getSomething,
        ...
    }
    

    and now you can call local functions as shown in the final version of the jsfiddle:

    app.factory('testSO', function () {
        var getSomething = function () {
            console.log('return getsomething');
            getData();
        };
    ...
    

    The original service has something important in it: var self = this; . Some people use var that = this. It's a workaround for an error in ECMA. In the case of the original code, it's used to "put everything in one object". Functions (properties that happen to be functions) in self need a reference to know where the function you want to call is. Try it yourself here http://jsfiddle.net/Z2MVt/7/

    0 讨论(0)
提交回复
热议问题