![](/img/trans.png)
[英]Share data list between unrelated components instantly RxJS Angular
[英]how to sync data between unrelated components with different route in angular (rxjs 6)
我在使用不同的路由在两个不相关的组件之间同步数据时遇到问题。
如果我这样做,它将起作用:
但是我需要在单独的路由上使用两个组件:localhost:4200 / a(componentA)localhost:4200 / b(componentB)
这里的代码:服务:
private messageSource = new BehaviorSubject('default');
currentMessage = this.messageSource.asObservable();
constructor() {}
changeMessage(message: string) {
this.messageSource.next(message)
}
componentA:
message: string;
constructor(private ts: StoreService) {}
ngOnInit() {
this.ts.currentMessage.subscribe(message => this.message = message)
}
HTML:
{{message}}
以componentB:
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}}
如果我在componentB中触发onChange函数,则在两个组件中都应显示“ FROM ACTIVATOR”:
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 {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.