Currently I'm trying to inject some kind of settings class into the application.
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class Settings {
private apiUrl: string = '';
private location: string = '';
private language: string = 'en';
constructor() {
if(localStorage.getItem('apiUrl')) this.apiUrl = localStorage.getItem('apiUrl');
if(localStorage.getItem('location')) this.location = localStorage.getItem('location');
if(localStorage.getItem('language')) this.language = localStorage.getItem('language');
}
getApiUrl(): string {
return this.apiUrl;
}
getLocation(): string {
return this.location;
}
getLanguage(): string {
return this.language;
}
setApiUrl(apiUrl: string): void {
this.apiUrl = apiUrl;
localStorage.setItem('apiUrl', apiUrl);
}
setLocation(location: string): void {
this.location = location;
localStorage.setItem('location', location);
}
setLanguage(language: string): void {
this.language = language;
localStorage.setItem('language', language);
}
}
This is my settings class...
What I try to do next is inject in through the whole application (since settings will be used a lot). For this I think the best way is to do this with the bootstrap() function. So this is my bootstrap function:
bootstrap(AppComponent, [Settings])
I did insert it into the constructor in the service I want to use the apiUrl setting:
@Injectable()
export class UserService {
constructor(private _settings: Settings, private _http:Http) { }
}
but for some reason when running the application I got an error in the UserService saying that the first parameter of the constructor (_settings) is undefined..
I've been trying different things but didn't find a working solution yet..
Did you forget to import the Settings class in your UserService?
You're not listing the top of your UserService...
Ok, so after trying many things I found out what the problem was.
I had a TS file containing all the exports for each folder I have..
I do have this core folder, containing the Settings class and a file called core.ts.
When I did: import { Settings } from './core';
it didn't work. But when I do: import { Settings } from './core/settings
, it does work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.