In my Angular2 app, I need to share an object between components. Here is how I'm attempting to do this:
First component source code:
/* app.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.html',
directives: [Grid],
providers: [ConfigService]
})
export class AppComponent {
public size: number;
public square: number;
constructor(_configService: ConfigService) {
this.size = 16;
this.square = Math.sqrt(this.size);
_configService.setOption('size', this.size);
_configService.setOption('square', this.square);
}
}
Second component source code:
/* grid.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'grid',
templateUrl: 'app/templates/grid.html',
providers: [ConfigService]
})
export class Grid {
public config;
public header = [];
constructor(_configService: ConfigService) {
this.config = _configService.getConfig();
}
Lastly, the ConfigService:
/* config.service.ts */
import {Injectable} from 'angular2/core';
@Injectable()
export class ConfigService {
private config = {};
setOption(option, value) {
this.config[option] = value;
}
getConfig() {
return this.config;
}
}
The issue I'm facing is that the data is not being shared between components. Despite filling the object in app.component.ts, it's empty when accessed in grid.component.ts.
I've tried following documentation and tutorials without success. What could be causing this problem?
Thank you
SOLVED
The problem was caused by injecting ConfigService twice - once in the bootstrap of the application and again where it's being used. Removing the providers
setting resolved the issue!