I have the following files:
/src/app/app.module.ts
...
@NgModule({
...
providers: [
StatusBar,
SplashScreen,
Storage,
ConfigService,
AuthService,
TodoService,
]
...
})
export class AppModule { }
/src/providers/config.service.ts
import { Injectable } from '@angular/core';
export interface HashTable<T> {
[key: string]: T;
}
@Injectable()
export class ConfigService {
config: HashTable<String> = {
'baseUrl': 'http://127.0.0.1:8080',
};
constructor() { }
getConfig(): HashTable<String> {
return this.config;
}
}
/src/providers/todo.service.ts
import { Injectable, OnInit } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { ConfigService, HashTable } from './config.service';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/map';
@Injectable()
export class TodoService implements OnInit {
config: HashTable<String>;
constructor(private http: Http, private configService: ConfigService, private authService: AuthService) {
// this.getConfig();
}
ngOnInit() {
this.getConfig();
}
getConfig(): void {
this.config = this.configService.getConfig();
}
getTodos() {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Authorization', this.authService.token);
this.http
.get(
this.config['baseUrl'] + '/api/todos',
{ headers: headers }
)
.map(res => res.json())
.subscribe(
data => {
resolve(data);
},
err => {
reject(err);
}
);
});
}
}
In the file: todo.service.ts...
The ngOnInit()
is not getting trigged. I need this to get trigged in order that the method: this.getConfig()
get called.
In the other hand, if I uncomment the line inside the constructor (same file) everything works fine but I don't want that way because I hope the ngOnInit
get called. I have read on some places that you should call the service load, in this case: this.getConfig();
inside the ngOnInit
.
My goal with all this is to use a file to store configuration values for the application. Actually this code works fine if I uncomment the line inside the constructor but I'm trying to get adjusted to the standards.
Any idea on this?
Thanks.