[英]how to sync data between unrelated components with different route in angular (rxjs 6)
I have problem syncing data between two unrelated components with different route. 我在使用不同的路由在两个不相关的组件之间同步数据时遇到问题。
if I do this it works: 如果我这样做,它将起作用:
But I need the two components on a separate route: localhost:4200/a (componentA) localhost:4200/b (componentB) 但是我需要在单独的路由上使用两个组件:localhost:4200 / a(componentA)localhost:4200 / b(componentB)
here the code: service: 这里的代码:服务:
private messageSource = new BehaviorSubject('default');
currentMessage = this.messageSource.asObservable();
constructor() {}
changeMessage(message: string) {
this.messageSource.next(message)
}
componentA: componentA:
message: string;
constructor(private ts: StoreService) {}
ngOnInit() {
this.ts.currentMessage.subscribe(message => this.message = message)
}
html: HTML:
{{message}}
componentB: 以componentB:
message: string;
constructor(private ts: StoreService) { }
ngOnInit() {this.ts.currentMessage.subscribe(message => this.message = message)}
onChange() {
this.ts.changeMessage('FROM ACTIVATOR');
}
html: HTML:
<button type="button" (click)="onChange()">Activate!</button>
{{message}}
if I trigger onChange function in componentB it should display 'FROM ACTIVATOR' in both components: 如果我在componentB中触发onChange函数,则在两个组件中都应显示“ FROM ACTIVATOR”:
StoreService should be registered in module providers as below: StoreService应该在模块提供者中注册,如下所示:
@NgModule({
declarations: [ AppComponent],
imports: [
AppRoutingModule,
BrowserModule, FormsModule, HttpModule
],
bootstrap: [ AppComponent ],
providers: [StoreService] // Injected here
})
export class AppModule { }
With Angular7+ we can decorate the service as singleton by following 使用Angular7 +,我们可以按照以下步骤将服务装饰为单例
@Injectable({
providedIn: 'root'
})
export class StoreService {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.