⚠️ This lesson is retired and might contain outdated information.

Share Services and Data with Angular 2 Dependency Injection

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 2 years ago

The Angular CLI generates Services using a simple command. After your Service is generated, you can easily provide and share it to the rest of your application using Angular 2's Dependency Injection. This lesson walks through creating a Service with the Angular CLI then providing it to your application module.

[00:00] Use the Angular CLI to generate a service. Service can just be with S or the full word Service. Then the name of the service. I'll call mine Mail. Hit enter and you'll see it generates two files, our mail service and the spec for that, and the warning that it's not provided.

[00:19] Let's go ahead and provide it. Do that in your app module. In providers we'll say mail service, and I'm going to let WebStorm automatically import this for me. You'll see it's added up here.

[00:32] Now that it's provided in this app module, if you go to your app component, you can inject it in the constructor of your app component. I'm going to say Private mail is a mail service, and I'll inject that again. Make sure your import is pointing to the proper service, so importing mail from mail service.

[00:54] Now whatever I put on mail service...If I navigate back to it, and say that I have a message and the message is, "You've got mail." Then hop back over to your component. Underneath my simple form I can say mail -- which is my service -- .message. Hit save and then this will refresh and you'll see the message, "You've got mail" underneath my simple form, the simple form with "You've got mail" underneath it.

leaf
leaf
~ 7 years ago

I'm getting an error "main.ts:12Uncaught Error: Module build failed: Error:..." after editing 'providers: [MailService],' at app.module.ts, and it didn't automatically imported for me. How can I fix it ?

Cekootje
Cekootje
~ 7 years ago

How comes that when generating a service, ng puts the files right in the app root folder? And creating a component showed that it gets generated inside its own folder. Are there guiding lines for this that ng is following?

vtechmonkey
vtechmonkey
~ 7 years ago

message needs a type of string in mail.service or you get a type error. message : string =You've got mail!;

Javril Bavogui
Javril Bavogui
~ 7 years ago

Not working

Vinícius Mussato
Vinícius Mussato
~ 5 years ago

Had to change the private to public on app.component.ts in order to the example fully work. Its propably related to Aot on angular 8. https://stackoverflow.com/questions/45520838/identifier-refers-to-a-private-member-of-the-component

Nil Hidalgo
Nil Hidalgo
~ 4 years ago

public message = 'You got mail';

Markdown supported.
Become a member to join the discussionEnroll Today