如何在 Angular 中具有不同路由的不相关组件之间同步数据 (RXJS 6)



我在两个具有不同路由的不相关组件之间同步数据时遇到问题。

如果我这样做,它可以工作:

但是我需要在单独的路由上安装两个组件: 本地主机:4200/A (组件 A( 本地主机:4200/B (组件 B(

这里的代码: 服务:

private messageSource = new BehaviorSubject('default');
currentMessage = this.messageSource.asObservable();
constructor() {}
changeMessage(message: string) {
this.messageSource.next(message)
}

组件 A:

message: string;
constructor(private ts: StoreService) {}
ngOnInit() {
this.ts.currentMessage.subscribe(message => this.message = message)
}

.html:

{{message}}

组件 B:

message: string;
constructor(private ts: StoreService) { }
ngOnInit() {this.ts.currentMessage.subscribe(message => this.message = message)}
onChange() {
this.ts.changeMessage('FROM ACTIVATOR');
}

.html:

<button type="button" (click)="onChange()">Activate!</button>
{{message}}

如果我在组件 B 中触发 onChange 函数,它应该在两个组件中都显示"来自激活器":

工作堆栈闪电战

StoreService 应在模块提供程序中注册,如下所示:

@NgModule({
declarations: [ AppComponent],
imports: [ 
AppRoutingModule, 
BrowserModule, FormsModule, HttpModule 
],
bootstrap: [ AppComponent ],
providers: [StoreService] // Injected here
})
export class AppModule { }

使用 Angular7+,我们可以通过以下方式将服务装饰为单例

@Injectable({
providedIn: 'root'
})
export class StoreService {
}

最新更新