我有angular2 v4.0.1项目,我正在使用组件路由器进行路由。我正在尝试创建一个共享(单例)服务,作为所有组件的数据存储。如果单个组件更新服务的值,则其他组件将具有该值。但是如果组件不是父组件的子组件,那么subscribe
不会被触发。
我有一个主AppComponent.ts,其他组件通过组件路由器加载。
我没有为每个组件使用单独的提供程序,我在根模块的@NgModule声明中注入了该服务。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule,JsonpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import {RouterModule, Routes} from '@angular/router';
import { ConfirmComponent } from './confirm.component';
import { AppComponent } from './app.component';
import { OtherComponent } from './other.component';
import { SomeComponent } from './some.component';
import { PlaceholderDirective } from './directives/placeholder.directive';
import { StorageService } from "./storage.service";
//app routes
const appRoutes: Routes = [
{path:'', redirectTo: '/home', pathMatch: 'full'},
{path:'home',component:AppComponent},
{path:'other',component:OtherComponent},
{path:'some',component:SomeComponent},
]
@NgModule({
imports: [ RouterModule.forRoot(appRoutes),BrowserModule, HttpModule,JsonpModule, FormsModule],
declarations: [ AppComponent, OtherComponent,SomeComponent, ConfirmComponent,PlaceholderDirective ],
providers:[StorageService],
bootstrap: [ AppComponent ],
entryComponents: [
ConfirmComponent
],
})
export class AppModule { }
import {Injectable,EventEmitter} from '@angular/core';
import { Subject } from "rxjs/Subject";
@Injectable()
export class StorageService {
name: any;
nameChange: Subject<string> = new Subject<string>();
constructor() {
this.name = "Jack";
}
change(){
this.name = 'Jane';
this.nameChange.next(this.name);
}
}
import { Component } from '@angular/core';
import { StorageService } from "./storage.service";
@Component({
selector: 'some',
template: `<p>{{storage.name}}</p><a (click)='change();'>Change</a>`,
})
export class SomeComponent {
constructor(
private storage : StorageService
){
setTimeout( () =>
this.storage.change(),2000);
}
change(){
this.storage.change();
}
}
import { Component } from '@angular/core';
import { StorageService } from "./storage.service";
import { Subscription } from "rxjs/Subscription";
@Component({
selector: 'other',
template: `<p>{{name}}</p>`,
})
export class OtherComponent {
name:string;
subscription: Subscription;
constructor(
private storage : StorageService,
){
this.name = this.storage.name;
this.subscription = this.storage.nameChange.subscribe((value) => {
this.name = value;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}