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:

ngDI-Copy

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

ngDI3-Copy

This problem was occurring using the following Angular environment:

ngDI2

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:

ngDI4-After

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

ngDI5-After-Copy

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: