0

As far as I understand Angularjs services are created by passing in a Contructor function:

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

  this.method1 =  function(){

   }
});

Angular runs this function with the new operator.

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

Can someone shed some light on what's going on here ?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

As a formal parameter, me does not need to be redeclared with var. me = me || "Mark"; will do the job.
1

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.then(function(user) {
    if (!user.loggedIn) {
       // reload the login route
       $location.path(facebookConfigSettings.loginPath || facebookConfigDefaults.loginPath);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.