Creating your own services in AngularJS can be confusing. What are the differences between an AngularJS module's Service, Provider and Factory functions? This lesson shows how Angular's service function is just a constructor function.
The implementation of the function will simply be to return, "Hi. I am," and then concatenate on the name of the Droid. Now that we have our service, we can create an instance of it by creating a local variable. We'll say Droid in this case, and calling new on the Droid service.
When I say that, we'll get, "Hi. I'm R2D2," down here in the console, because I'm just in an empty page. If I were to switch from the empty page over to an Angular application that I have ready, we can look at how we can take this constructor function, and make it work inside of an Angular application.
If we paste it in here first, we need to tell Angular about our constructor function. We do that by calling the .service method. The first argument to the service method is the service name. We'll just call it Droid. The second argument is the implementation, which is the constructor function itself, so we'll pass in the Droid service.
If we ask for an instance of the Droid service here in our controller, because we registered this function as a service with Angular, Angular will effectively run this line of code for us. It will apply the new operator to the Droid service function that we passed it, thus giving us back an instance of a Droid.
We can then work with that instance the Droid, assign a name as we did before to R2D2, and we can use our Droid controller's message property which outputs the page to logout the Droid speaking. If I save it here in the middle of the page we see, "Hi. I'm R2D2."
To quickly recap, if you want to use a constructor function inside your Angular application to create an object as we have done here, you'll need to tell Angular that the function is a constructor function, by registering it with the .service method off of the module.
This tells Angular that it needs to effectively run this line of code, that is create a new instance of your Droid service. Once Angular has an instance of the service, it will dependency inject it wherever you ask for it.