TypeScript is used heavily as we build up our application, but TypeScript isn’t required. If you want to Inject a Service without using TypeScript, you’ll need to understand the @Inject
decorator. The @Inject
decorator also allows you to provide any value or object that you need to share throughout your application without having to create a service.
[00:00] Now you'll notice in our providers that we provided the class mail service and then in our app component we injected the mail service by the type over here. This matches with this here.
[00:13] You can also do this by passing in an object, saying Provide and then any value. I'm just going to say a string of mail, then say Use class mail service. Then back in my app component, instead of injecting by type, I can actually use and inject decorator. Make sure to import that.
[00:34] Then I'm going to inject mail because this string matches with this provide string that I added here. It will know to use this class of mail service. When I switch back to my component, now we can actually delete this line where I import the class, and I no longer have a reference to it. It's just going to know to grab this as a class of the providers, create the instance, and then use it just as we did before. If I hit save, you'll see the exact same result over in the browser when it refreshes.
[01:04] Providing with these objects is also very useful if I need to provide something like an API. I'll say Object provide API. Now I can say Use value HTTP//localhost 3000 or wherever it would be. Now we can inject this API where I use the same syntax. Now I inject API. I'll call this "API," and then I'll just go ahead and show API on the page with a simple break between these two values. I'll hit save.
[01:38] You can see we can now use this "API" string, this value, throughout our application and keep it consistent just by injecting this string which matches the key in our injector because we provided it here.