Angular Service Definition: service or factory

雨燕双飞 提交于 2019-11-28 01:16:01

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!