【问题标题】:Angular RXJS Observables or Subjects passing numbers InternallyAngular RXJS Observables 或 Subjects 在内部传递数字
【发布时间】:2018-02-28 16:11:36
【问题描述】:

在 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 信息源一无所获。

【问题讨论】:

  • 你具体想做什么?
  • 将一个数字从一个组件传递到另一个组件,所有这些都位于文件树的末尾。我正在使用@Input 链。我想切换到可观察对象和服务。
  • 有什么问题?
  • 为什么不能insertData(number)
  • 您能否发布更多您的代码(作为代码,而不是屏幕截图)?

标签: angular rxjs observable behaviorsubject subject-observer


【解决方案1】:

这是一个如何将 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 功能。

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

exact 与 getter/setter 的功能相同,而不是这里的 Subject/BehaviorSubject:https://github.com/DeborahK/Angular-Communication/tree/master/APM-FinalWithGetters

【讨论】:

  • 我认为 Angular 5 开发人员被鼓励全面切换到 observable?在内部价值交换到 getter 和 setter 的情况下是否有更多好处?因为我的许多组件都在等待这些值,而且它们更新非常频繁,所以我在重构开始时选择了 Observables。
  • Angular 的变更检测已经在您的模板绑定到结果时为您处理通知。在这种情况下,使用 getter/setter 会更简单、更直接。但是,当您需要通知或想要处理异步操作时,Observables 是您的最佳选择(例如,与 Promise 相比)。
  • 因为不是我的例子,和提供的github不匹配。如果您有更准确的答案,请随时复制我的代码,将其更改为与您的数字示例相匹配,然后将其标记为您的答案。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2017-03-20
  • 1970-01-01
  • 2017-12-17
  • 2016-09-07
  • 1970-01-01
相关资源
最近更新 更多