1

I'm using angular 2 inside of a ASP.NET Core application, but that isn't important for this issue. Part of my current task is to get configuration values from the server into my angular application.

I have the settings flowing through to the point that I am writing one setting into my layout like so:

<script>
    var BASE_WEB_API_URL = '@appSettings.BaseUrls.Api';
</script>

And this is working, which I have verified by looking at the markup. Now, what I want is to make an appsettings class that I can inject via DI into my services and components that need it. Here is what I have so far:

import { Injectable } from '@angular/core';

@Injectable()
export class AppSettings {
    public BASE_WEB_API_URL: string = window['BASE_WEB_API_URL'];
}

Very simple and straight forward and it should allow me to inject my server variables. However, I get an error when I try to use it.

Error: Uncaught (in promise): Error: No provider for AppSettings!

So, I thought my problem was that it wasn't listed in the imports in my app module. So I added it only to get this error:

Error: Unexpected value 'AppSettings' imported by the module 'AppModule'

So, googling this error lead me to a post saying it maybe needed to be in the bootstrap section, so I tried that next only to get a new error message.

Error: No Directive annotation found on AppSettings

I'm very green to Angular 2, so these errors are throwing me off. Any thoughts on what I am doing wrong?

Thank you

Josh
  • 16,286
  • 25
  • 113
  • 158
  • 2
    Don't put it into the module's `imports` metadata, put it into `providers`. – pe8ter Nov 13 '16 at 06:10
  • Excellent suggestion. However, now I have a "window is not defined" error happening inside my appsettings.ts – Josh Nov 13 '16 at 06:29
  • Compile error or runtime error? – pe8ter Nov 13 '16 at 06:45
  • This appears to be a compile time error. I have searched around and found some posts on writing a window provider, but all solutions seem to error out. [Like this one](https://stackoverflow.com/questions/34177221/angular2-how-to-inject-window-into-an-angular2-service) – Josh Nov 13 '16 at 06:53
  • Shouldn't need anything special to access the window. Don't know what to tell you. – pe8ter Nov 13 '16 at 07:30
  • I discovered the issue with window not defined. You cannot use window if you are using server side pre-processing. There is no window on the server side so it fails. – Josh Nov 16 '16 at 18:49

1 Answers1

1

Put injectables into your module's providers metadata, not imports.

pe8ter
  • 1,263
  • 12
  • 10