使用Angular 2中的Observable和Subject在服务的多个组件之间进行通信 [英] Communication between multiple components with a service by using Observable and Subject in Angular 2

查看:527
本文介绍了使用Angular 2中的Observable和Subject在服务的多个组件之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是rxjs的新手,所以我想问一个关于Angular 2ObservablesBehaviorSubject/Subject的问题.

I am new to rxjs, so I would like to ask a question regarding Angular 2, Observables and BehaviorSubject/Subject.

所以,我要实现的是:在ComponentA内的buttononclick通知其他组件,例如ComponentBComponentC.

So, what I want to achieve is : onclick of a button inside a ComponentA to notify other components for example ComponentB, ComponentC.

到目前为止,我要做的是创建一个service:

What I did so far is to create a service:

private isMenuOpenBS = new BehaviorSubject(false);

  toggleMenu(): void {
    this.isMenuOpenBS.next(!this.isMenuOpenBS.getValue());
  }

  getMenuState(): Observable<boolean> {
    return this.isMenuOpenBS.asObservable();
  }

然后具有一个与provide menuService相同的组成部分的是调用this.menuService.toggleMenu(),它会更改BehaviorSubject的值.代码:

Then having one component with provide menuService is calling the this.menuService.toggleMenu() which changes the value of the BehaviorSubject. Code :

toggleMenu(): void {
    this.menuService.toggleMenu();
    this.menuService.isMenuOpenBS.subscribe(
      (data) => {
        console.log(data)
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }

OnInit() subscribesgetMenuState()的另一个组件,它是Observable,但是它仅在OnInit()上获得值.代码:

And another component that OnInit() subscribes to the getMenuState() which is an Observable, but it get's values only on OnInit(). Code:

ngOnInit(): void {
    this.menuService.getMenuState().subscribe(
      (data)=>{
        this.messages = data;
        console.log('nav component');
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }

从不调用complete函数.

有什么想法我在做错什么,或者如果我在逻辑上缺少什么?

Any ideas what am I doing wrong or if i am missing something in the logic ?

-

因此,为了进一步说明问题,我可以看到可观察对象具有oninit的第一个值,但没有其他值.之后没有错误,没有完成,也没有下一个"值,这是错误的,因为我正在从主题发送新值.最终,问题出在组件的提供者列表上,而不是可观察对象或主题问题,但是在解决问题之前,很难发现问题出在哪里.

Edit : So, to explain a bit more the problem was that I could see the first value that the observable had oninit but nothing else. No error no complete after that or no "next" value which was wrong since I was sending new values from the subject. In the end the problem was with the provider list of the components and not a problem of observables or subjects, but before solving the problem it wasn't easy to see that the problem was there.

推荐答案

几件事...

  1. 您不需要将您的BehaviorSubject作为可观察对象返回,您应该可以订阅可观察对象.
  2. 您不应在每次调用toggle函数时都继续订阅该服务.这样您将创建许多订阅.如果您从上面接受了我的建议,则只需记录getValue()函数的返回即可.

很高兴您解决了这个问题!

Glad you resolved it though!

这篇关于使用Angular 2中的Observable和Subject在服务的多个组件之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆