Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Keep service instances when changing routes

I have three components which are basically using all the same DataService. Not because of the same data, but because of the exactly same methods and patterns:

@Component({
    templateUrl: './data-list-1.html',
})
export class DataOne  {
    constructor(private dataService:DataService) {
    }
}

@Component({
    templateUrl: './data-list-2.html',
})
export class DataTwo  {
    constructor(private dataService:DataService) {
    }
}

@Component({
    templateUrl: './data-list-3.html',
})
export class DataThree  {
    constructor(private dataService:DataService) {
    }
}

I can switch between the components via routes. So one question is how can I keep the states of the different DataServices within the components? As far as I know that requires different instances of DataService, because each holds different data:

@Component({
    templateUrl: './data-list-1.html',
})
export class DataOne  {
    constructor() {
        this.dataService = new DataService();
    }
}

@Component({
    templateUrl: './data-list-2.html',
})
export class DataTwo  {
    constructor() {
        this.dataService = new DataService();
    }
}

@Component({
    templateUrl: './data-list-3.html',
})
export class DataThree  {
    constructor() {
        this.dataService = new DataService();
    }
}

Now although they have the same pattern of DataService they all have their own instance with their own data. But one problem isn't solved so far. How can I keep the instance of DataService when I change routes?

like image 420
Trevor Hector Avatar asked Mar 17 '26 05:03

Trevor Hector


1 Answers

You need to provide the DataService at the AppModule level and not on each of the components.

@NgModule({
    imports: [AppRoutingModule,
        BrowserModule,
        FormsModule,
        HttpModule,
        ReactiveFormsModule],       // module dependencies
    declarations: [],           // components and directives
    bootstrap: [AppComponent],      // root component
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    providers: [DataService]
})
export class AppModule { }

To specify the service so that each component and it's children get there own instance of the service you would want to provide the service at the component level like so:

@Component({
    selector: "some",
    templateUrl: "./some.component.html",
    providers: [DataService]
})
export class SomeComponent {}
like image 135
Teddy Sterne Avatar answered Mar 20 '26 04:03

Teddy Sterne