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.
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?
message needs a type of string in mail.service or you get a type error.
message : string =
You've got mail!;
Not working
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
public message = 'You got mail';
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 ?