Fixed NG Book 5 Dependency Injection Page 175

I have been working through the NG2 book on Angular 5 and became stuck when trying to get an example on Dependency Injection to work.

Here is part of the problematic code I was unable to run:

When running the sample, the page did not load and part of the console message reported by Chrome is shown below:

This problem was occurring using the following Angular environment:

Starting with the user-demo-component.ts file and after commenting out various parts of the code within this file I tracked the problem to the constructor:

constructor(private userService: UserService) {

Fortunately StackOverflow to the rescue and this answer provided the fix.  I made the following change to user-demo-component.ts whereby I added providers to the @Component decorator

  providers: [UserService] 

The @Component decorator should now look like this:

Why does the completed example work without this fix?

Good question! If you have read any of NG2 book you will know that all the code examples in the book come with the source ready for you to try out rather than typing. When I checked the example and ran them I couldn’t see a similar change yet the code worked as expected so I will need to continue digging to ascertain why the supplied version works.

I will update the post once I have found out.

Update 23/04/2018

The completed example uses a different version of Angular and typescript. Here is the output from ng –version

The completed example which works uses Angular 5.2.0 whereas the version of Angular I am using is 5.2.9.