Search code examples
angularangular2-services

Single instance of a service class in angular2 Module / app


I am writing angular2 application which have two component. Both the component take data from one service. I have included this service in two of my Component and I want when ever there is any data change in any Component, it should change the other component view as both are getting date from same service and these component changes data in the services.

bootstrap application

//main.ts
platformBrowserDynamic().bootstrapModule(AppModule);

App module code:

//app.module.ts
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent, OfferFilter, OfferListing],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app component

//app.component.ts
@Component({
  selector: 'app',
  template: `<first-component></first-component>
    <second-component></second-component>`,
})
export class AppComponent {
}

First component

@Component({
    selector: 'first-component',
    template: `
        <div class="manage">
            ...
        </div>
    `,
    providers: [WidgetResourcesList]

})
export class OfferFilter {

    constructor(public widgetResourcesList: WidgetResourcesList) {
    }
    selectFilter($event: any) {
        this.widgetResourcesList.serUserSelection(value, checked);
    }

}

second component

@Component({
    selector: 'second-component',
    template: `
    <table>
    ....
    </table>
    `,
    providers: [WidgetResourcesList]
})
export class OfferListing {
    constructor(public widgetResourcesList: WidgetResourcesList) {
    }
}

WidgetResourcesList class which provided as provides in components

export class WidgetResourcesList {

    //noinspection TypeScriptUnresolvedVariable
    private widgetResources = window.widgetResources;
    private userSelection: Array<any> = [];
    private header: Array<any>;
    private offerList: Array<any>;

    setOffer(header: Array<any>, offerList: Array<any>) {
        this.header = header==null? [] : header;
        this.offerList = offerList==null? [] : offerList;
    }

    getOffer() {
        return {'header': this.header, 'offerList': this.offerList};
    }

    private filterList : Array<any> = [
        {
            'id': 'VIDEO',
            'name': 'Television',
            'desc': 'Cable TV and On Demand',
            'checked': false
        },
        {
            'id': 'XHS',
            'name': 'Home',
            'desc': 'Security, control and more',
            'checked': false
        },
    ];

    getFilterList() {
        return this.filterList;
    }

    serUserSelection(id: String, checked: boolean) {
        if(checked) {
            this.userSelection.push(id);
        } else {
            if(this.userSelection.indexOf(id) >=0){
                this.userSelection.splice(this.userSelection.indexOf(id),1);
            }
        }
    }

    getOffersForPhone() {
        let userSelectionStr = this.userSelection.sort().join('$');
        if(userSelectionStr==="") {
            userSelectionStr = "VIDEO"
        }
        return this.getOffer();
    }
}

What I am doing wrong?


Solution

  • You need to add WidgetResourcesList to the providers in the Module. And you need to remove it from the providers in the components.

    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ AppComponent, OfferFilter, OfferListing],
      bootstrap: [ AppComponent ],
      providers: [ WidgetResourcesList ]
    })
    export class AppModule { }
    

    When you add a service to the providers of a component every time that component is instantiated all of the providers are also instantiated and so you get different instances of the service.