MainComponent
からTestListComponent
にナビゲートするたびに、TestListComponentコンストラクタが起動され、ObservableService
の新しいインスタンスが作成されます。リンクをクリックすると、コンソールに重複したメッセージが表示されます。多分角張った問題、どんな助けですか?遅延ロードされたモジュールは、毎回親サービスの複数のインスタンスを作成します。
main.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {MainRoutingModule} from "./main-routing.module";
import {MainComponent} from './main.component';
import {ObservableService} from "../../core/services/observable.service";
@NgModule({
imports: [
BrowserModule,
MainRoutingModule,
],
declarations: [MainComponent],
providers: [ObservableService],
bootstrap: [
MainComponent
]
})
export class MainModule { }
main.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
export const routes: Routes = [
{ path: 'tests', loadChildren: 'angular/app/modules/test-list/test-list.module#TestListModule'},
{ path: '**', redirectTo: '' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class MainRoutingModule {}
observable.service.ts
import { Injectable } from '@angular/core';
import {Subject} from "rxjs/Rx";
import 'rxjs/add/operator/map'
@Injectable()
export class ObservableService {
// Observable string sources
private changeLanguageStatus = new Subject<Object>();
// Observable string streams
changeLanguageStatus$ = this.changeLanguageStatus.asObservable();
constructor(){}
/**
* Change language event
* @param params
*/
changeLanguageEvent(params: Object){
this.changeLanguageStatus.next(params);
}
}
テストlist.module.ts
import { NgModule } from '@angular/core';
import {TestListComponent} from "./test-list.component";
@NgModule({
declarations: [
TestListComponent
]
})
export class TestListModule {}
テストlist.component.ts
import {Component} from '@angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
@Component({
moduleId: module.id,
selector: 'st-test-list',
templateUrl: 'test-list.component.html'
})
export class TestListComponent {
constructor(private observableService:ObservableService) {
observableService.changeLanguageStatus$.subscribe(
data => {
console.log('Test', data);
});
}
}
main.component.ts
import {Component, ViewChild} from '@angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
@Component({
moduleId: module.id,
selector: 'st-main',
templateUrl: 'main.component.html'
})
export class MainComponent {
constructor(private observableService:ObservableService) {}
changeLanguage(lang){
this.observableService.changeLanguageEvent({type: lang});
}
}
main.component.html
<a href="" (click)="changeLanguage('en')"></a>
<!--Dynamic content-->
<router-outlet></router-outlet>
この問題に関連している可能性があります.https://github.com/angular/angular/issues/12869 – glendaviesnz