繁体   English   中英

角度RXJS可观察变量或主题内部传递数字

[英]Angular RXJS Observables or Subjects passing numbers Internally

在Angular 5应用程序(无API)中传递数字的正确RXJS方法是什么?

我已经成功地通过Subject传递了一个布尔值:

服务内容:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class IsOpened {

  data = new Subject();

  constructor() {}

  insertData(data){
    this.data.next(data);
  }
}

发射器:

toggle(){
    this.opening = !this.opening;
    this._isOpened.insertData(this.opening);
}

听众:

ngAfterViewInit() {
    this._isOpened.data.subscribe((value) => {
      if(value) this.opened = true;
      else this.opened = false;
    }});
}

我在监听器中作弊,因为我不存储接收到的值,而是对其进行评估并重新创建布尔值。

为我工作,适合几行。

我不能对数字做同样的事情。

在此处输入图片说明

我怎么用数字呢? 与数组?

Google和许多RXJS信息源什么都没有产生。

这是有关如何将Subject / BehaviorSubject与对象一起使用的示例。 同样的技术也适用于数字。

服务

export class ProductService {
    private products: IProduct[];

    // Private to encapsulate it and prevent any other code from
    // calling .next directly
    private selectedProductSource = new BehaviorSubject<IProduct | null>(null);

    // Publicly expose the read-only observable portion of the subject
    selectedProductChanges$ = this.selectedProductSource.asObservable();

    changeSelectedProduct(selectedProduct: IProduct | null): void {
        this.selectedProductSource.next(selectedProduct);
    }
}

组件设置值

  onSelected(product: IProduct): void {
    this.productService.changeSelectedProduct(product);
  }

在这种情况下,当用户在一个组件中选择某个东西时,该选择将广播到其他几个组件。

组件读取值

ngOnInit() {
    this.productService.selectedProductChanges$.subscribe(
        selectedProduct => this.product = selectedProduct
    );
}

在此示例中,读取值的组件将其存储到其自己的局部变量中。 该变量用于绑定,UI会根据所选产品进行更改。

注意:您可以使用没有主题/行为主题的getter / setter实现此SAME功能。

我在这里有一个使用Subject / BehaviorSubject的完整示例: https : //github.com/DeborahK/Angular-Communication/tree/master/APM-Final

并与getter / setter方法,而不是主题完全相同的功能/ BehaviorSubject这里: https://github.com/DeborahK/Angular-Communication/tree/master/APM-FinalWithGetters

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM