简体   繁体   English

角服务返回对象?

[英]Angular service returning object?

As far as I understand Angularjs services are created by passing in a Contructor function: 据我了解,Angularjs服务是通过传入Contructor函数创建的:

app.service('serviceName', function(){
  this.var1 = 'foo';

  this.method1 =  function(){

   }
});

Angular runs this function with the new operator. Angular使用new运算符运行此功能。

I was going through this service, and i don't see any "this" insider 我正在通过此服务,但没有看到任何“此”内部消息

https://github.com/shreya5/angular-facebook-utils/blob/master/src/scripts/facebookUser.js

Infact this function returns deferred.promise 实际上此函数返回deferred.promise

Can someone shed some light on what's going on here ? 有人可以阐明这里发生的事情吗?

You are free to choose whatever pattern you want. 您可以自由选择所需的任何模式。 Just because angular runs your function with new doesn't obligate you to use this nor does it require you to return the default object. 仅仅因为angular用new运行您的函数并不意味着您必须使用this也不要求您返回默认对象。

For example, this is a pretty nice idiom that I use in Angular services a lot: 例如,这是我在Angular服务中经常使用的一个非常好的习惯用法:

function myConstructor(me){  
    me = me || "Mark";
    return {
        name: me,
        sayit: function(){return "Say my name, " + me}
     };

 }
 var obj = new myConstructor("Steve");
 console.log(obj.sayit())
 console.log(obj.name)

The value returned from service depends on how it will be used. 服务返回的值取决于如何使用。 You are free to return whatever you want. 您可以自由退货。 From another file where this facebookUser will be used, it's used as a promise, facebookUser.then . 另一个将使用此facebookUser 文件中 ,将其用作保facebookUser.then

facebookUser.then(function(user) {
    if (!user.loggedIn) {
       // reload the login route
       $location.path(facebookConfigSettings.loginPath || facebookConfigDefaults.loginPath);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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