【问题标题】:how to sync data between unrelated components with different route in angular (rxjs 6)如何以角度(rxjs 6)在具有不同路由的不相关组件之间同步数据
【发布时间】:2019-09-12 17:08:27
【问题描述】:

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

如果我这样做,它会起作用:

但我需要在单独的路线上使用这两个组件: 本地主机:4200/a(组件A) localhost: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}}

如果我在 componentB 中触发 onChange 函数,它应该在两个组件中显示“FROM ACTIVATOR”:

【问题讨论】:

  • ...你是如何提供这项服务的,你确定它是单例吗?

标签: angular rxjs


【解决方案1】:

working stackblitz

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.com/edit/… 并在另一个选项卡上打开这个angular-router-basic-example-h1bqb7.stackblitz.io/catalog。
  • 您能详细说明一下吗? ...或者用你遇到的问题更新 stackblitz
  • 如果您在 2 个选项卡中运行应用程序,基本上您正在运行同一应用程序的 2 个实例。如果您想通过一个浏览器在多个应用程序之间共享数据,那么您必须将该数据添加到浏览器缓存中,例如本地存储等。有意义吗?
  • 您应该打开两个选项卡,按钮位于主路由的第一个选项卡中。 1.angular-router-basic-example-h1bqb7.stackblitz.io/home 2.angular-router-basic-example-h1bqb7.stackblitz.io/catalog(一个常见的电子商务场景,其中客户打开两个标签..产品标签和购物车标签..当客户在产品标签上添加产品或增加数量时..shopping-cart 标签应该更新。
  • hot observable to api?
猜你喜欢
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 2018-09-19
  • 2021-04-22
相关资源
最近更新 更多