Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Share Services and Data with Angular 2 Dependency Injection

    John LindquistJohn Lindquist
    5 - 6

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.

    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.

    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.

    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.