0

据我了解,Angularjs 服务是通过传入一个构造函数来创建的:

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

  this.method1 =  function(){

   }
});

Angular 使用new操作符运行这个函数。

我正在通过这项服务,我没有看到任何“这个”内幕

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

事实上这个函数返回 deferred.promise

有人可以阐明这里发生了什么吗?

4

2 回答 2

1

从服务返回的值取决于它的使用方式。您可以自由退回任何您想要的东西。从另一个将使用它的文件facebookUser,它被用作一个承诺,facebookUser.then.

facebookUser.then(function(user) {
    if (!user.loggedIn) {
       // reload the login route
       $location.path(facebookConfigSettings.loginPath || facebookConfigDefaults.loginPath);
    }
});
于 2014-08-01T23:23:13.293 回答
1

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.

For example, this is a pretty nice idiom that I use in Angular services a lot:

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)
于 2014-08-01T23:03:20.363 回答