2017-03-03 57 views
1

我有三个基本上都使用相同DataService的组件。不是因为相同的数据,而是因为完全相同的方法和模式:Angular 2在更改路线时保留服务实例

@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) { 
    } 
} 

我可以通过路由在组件之间切换。所以一个问题是我怎样才能保持组件中不同DataServices的状态?据我知道,需要DataService不同的情况下,由于各持不同的数据:

@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(); 
    } 
} 

现在虽然他们的DataService相同的模式,他们都有自己的实例与他们自己的数据。但目前尚未解决一个问题。如何在更改路由时保留DataService的实例?

+1

你在哪里提供' DataService'?如果您在更改路由时由路由器添加和删除的组件上提供它,则该服务实例也将被销毁并重新创建。您需要在父组件中提供它,但是如果路由组件被添加到同一父组件,它们将发生冲突。 –

+0

@GünterZöchbauer所有组件都属于同一模块。这就是我提供DataService的地方。 –

+0

如果你在模块中提供它,那么你不能有不同的实例(除了延迟加载的模块)并且状态不会丢失。 –

回答

1

您需要在AppModule级别提供DataService,而不是在每个组件上。

@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 { } 

指定服务,使每个组件和它的孩子们有自己的服务的情况下,你会想在组件级,像这样提供的服务:

@Component({ 
    selector: "some", 
    templateUrl: "./some.component.html", 
    providers: [DataService] 
}) 
export class SomeComponent {} 
+0

是的,这很清楚。所有组件都属于同一个模块。这就是我提供DataService的地方。 –

+0

你是否在你的组件中重新提供它们?如果不是,那么所有的组件应该得到相同的服务参考。 –

+0

是的,但我不想要相同的参考。每个应该有它自己的实例。 –