【问题标题】:Angular: How to correctly access data in ComponentAngular:如何正确访问组件中的数据
【发布时间】:2019-11-22 22:33:53
【问题描述】:

我想知道在组件中访问数据的正确方法是什么。我已经读过几次了,您应该让 Angular 模板处理订阅但是您将如何访问 component.ts 文件中某些方法的当前值?

假设我有以下组件:

@Component({...})
class TestComponent {

  testData: Observable<TestData>

  ngOnInit(){
    this.testData = this.service.getData().pipe(share())
  }
}

它有一个sendDataABCProperty,它将我们的 testData 的属性ABC 发送到某个任意服务。

  sendDataABCProperty() {
    this.testData.pipe(first()).subscribe(data => this.service.sendData(data.abc))
  }

现在,当使用上述方法时,我仍然必须订阅我的数据,这正是我试图阻止的。

另一种方法是复制数据而不使用流,但由于我试图使其更具反应性,这是我想避免的一种方式。

另一个例子是某种“显示和编辑”组件。 假设我从某个服务获取我的显示数据,然后我访问该服务以更新数据。但我需要(数据的)id。访问 id 的最佳方式是什么?在开头复制它(使用tap() / subscribe())?使用BehaviorSubject?还是完全不同的东西?

【问题讨论】:

  • 可以给我们介绍一下服务方法吗?
  • 如果不想订阅,可以使用tap()操作符代替subscribe()
  • 服务应该无关紧要。敲击技巧也没有,因为我仍然需要在某个地方订阅。我正在尝试改写它。

标签: angular rxjs reactive-programming


【解决方案1】:

您的帖子中有几个问题,我将解决有关获取 id 的部分。

我有一个显示产品列表的列表组件。用户单击产品以显示/编辑它。我用Subject/BehaviorSubject处理这个问题

服务中

  private productSelectedSubject = new BehaviorSubject<number>(0);
  productSelectedAction$ = this.productSelectedSubject.asObservable();

在组件中(当用户点击产品时)

  onSelected(productId: number): void {
    this.productService.selectedProductChanged(productId);
  }

服务中

然后,我在服务中有一个流属性,每次发出不同的选定产品时,它的管道都会自动重新执行:

  selectedProduct$ = combineLatest([
    this.products$,                    // Stream of all products
    this.productSelectedAction$
  ]).pipe(
    map(([products, selectedProductId]) =>
      products.find(product => product.id === selectedProductId)
    ),
    tap(product => console.log('selectedProduct', product)),
    // do whatever else needs to be done when a new product is selected
  );

这能回答你的那部分问题吗?

我这里有示例代码:https://github.com/DeborahK/Angular-RxJS

此视频也可能有用:https://www.youtube.com/watch?v=Z76QlSpYcck

【讨论】:

  • 是的,确实如此。因此,使用 BehaviorSubject 的方法似乎是可行的方法。
  • 如果你想采用响应式方法,那么代码应该通过将数据发送到流中来“传递”数据。任何正在“监视”该流更改的代码都会收到通知,并将获得“通过”的数据。
【解决方案2】:
  • 在订阅之前,您无法访问服务数据。但是,您可以使用管道修改数据。但请注意,修改仅在您订阅 observable 时发生。
  • 我不知道这是不是你想要的。您还可以使用 resolver 在组件加载之前获取数据并使用快照检索数据。这样您就不必在组件中订阅 observable。

请阅读本文了解更多详情,https://alligator.io/angular/route-resolvers/

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 2017-09-24
    • 2019-07-15
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多