如何在angular(rxjs 6)中不同路由的不相关组件之间同步数据
我无法在两个具有不同路由的不相关组件之间同步数据 如果我这样做,它会起作用: 但我需要一条单独的路线上的两个组件: 本地主机:4200/a(组件a) 本地主机:4200/b(组件b) 代码如下: 服务: 组成部分A:如何在angular(rxjs 6)中不同路由的不相关组件之间同步数据,angular,rxjs,Angular,Rxjs,我无法在两个具有不同路由的不相关组件之间同步数据 如果我这样做,它会起作用: 但我需要一条单独的路线上的两个组件: 本地主机:4200/a(组件a) 本地主机:4200/b(组件b) 代码如下: 服务: 组成部分A: message: string; constructor(private ts: StoreService) {} ngOnInit() { this.ts.currentMessage.subscribe(message => this.message =
message: string;
constructor(private ts: StoreService) {}
ngOnInit() {
this.ts.currentMessage.subscribe(message => this.message = message)
}
html:
组件B:
message: string;
constructor(private ts: StoreService) { }
ngOnInit() {this.ts.currentMessage.subscribe(message => this.message = message)}
onChange() {
this.ts.changeMessage('FROM ACTIVATOR');
}
html:
激活!
{{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 {
}
…您是如何提供此服务的?您是否确保它是一个单例服务?在您的示例中..您应该在一个浏览器选项卡上打开此服务。。这个在另一个标签上。你能详细说明一下吗。。。或者用您遇到的问题更新stackblitz,如果您在两个选项卡中运行应用程序,那么基本上您运行的是同一应用程序的两个实例。如果您想在一个浏览器中共享多个应用程序之间的数据,则必须将该数据添加到浏览器缓存(如本地存储和所有应用程序)中。有意义吗?你应该打开两个标签按钮在回家路线的第一个标签上。1.2.(一种常见的电子商务场景,其中客户打开两个选项卡..产品选项卡和购物车选项卡..当客户在产品选项卡上添加产品或增加数量时..应更新购物车选项卡。api是否可观察到热?
<button type="button" (click)="onChange()">Activate!</button>
{{message}}
@NgModule({
declarations: [ AppComponent],
imports: [
AppRoutingModule,
BrowserModule, FormsModule, HttpModule
],
bootstrap: [ AppComponent ],
providers: [StoreService] // Injected here
})
export class AppModule { }
@Injectable({
providedIn: 'root'
})
export class StoreService {
}