Injectors

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

Injectors inject your dependencies in your AngularJS application. For the most part it will automatically work when constructing objects (controllers) and provide the dependencies defined with your service/factory/provider, it can also be injected itself and be used for invoking methods with injection.

John Lindquist: Injectors and providers are pretty much like totally BFF's. What that means is that injectors allow the providers to come to all the parties. That means that if I use invoke here, which is basically just going to do the magical thing you see every time you pass in a function here, and you automatically get this stuff. This is shorthand for what's going on here.

This means that you can use the providers like this game provider, which just happens to be a factory. I can just use him anywhere, so if I say, "game title," hit refresh, you can see I've got StarCraft and Alert. Now, if you look into this a little bit, and we go to the debugger, take a step back to where invoke is, you can kind of see what's going on.

Where the key is game, it's looking up game and then it's going to use that key to build up some arguments. Then it will use the get service, because [inaudible 01:10] that's a little different to routing stuff and whatnot, that we talked about a bit before. Then it's going to look the guy up off the cache. If we look in the cache, you can see we have a game. If I look him up in the cache, it's going to have that game object, and return a guy with the name and title.

The cache has all the providers, and then the injector grabs provider, throws it into that function, and you are good to go. Basically, if you wanted another way to use the injector, you wouldn't use it like this often, where you look it up off the module. You can actually inject the injector, just because you want to be cool. Then you can use the injector the exact same way here.

I'm just going to grab all of this, and I can say, "Injector invoke." Then instead of injecting in game here, I guess I could just drop that in there. That should work the same. You can see StarCraft is still being injected off the game.

That's what the injector does. It just provides the invoked method to pass your providers into whatever function is being passed into it. We'll talk about the annotations later on, but for right now, this is how you use the injector. There's one injector per module. It's created along with the module. And that's it.