【问题标题】:Angular2 is this the right way to use Observables?Angular2 这是使用 Observables 的正确方法吗?
【发布时间】:2017-02-01 16:14:19
【问题描述】:

“订阅”和“取消订阅”如何与 Angular2 中的 Observable 一起使用?

我的架构如下:

  1. CRUD(Repo) 服务包含 CRUD 操作并返回一个 可观察
  2. 与 CRUD 对话的中间服务。该服务被注入到组件中并包含私有 BehaviorSubjects。我公开了底层的价值观

    get selectedClient(): Observable<Client> {
        return this._selectedClient.asObservable();
    }
    
    get clients(): Observable<Client[]> {
        return this._clients.asObservable();
    }
    
  3. 在组件级别,我通过订阅前面提到的 getter 来访问数据:

    deleteClient() {
     this.selectedClient.subscribe(actualClient => {
        this.clientStore.deleteClient(actualClient).subscribe(response => {
            if (response) {
                this.router.navigate(['/clients']);
            }
        });
     }).unsubscribe();
    }
    
    updateClient() {
      this.clientUpdateForm.submitClientForm().subscribe(client => {
            if (client) {
                this.growlService.showInfoMessage("Client updated", client.firstName + " " + client.lastName);
            }
      }).unsubscribe();
    }
    
    this.selectedClient.subscribe(client => {
        this.clientForm = this.clientUpdateForm.clientForm;
    }).unsubscribe();
    

首先我想问一下,这个设计有什么问题吗? 其次,什么时候需要退订,什么时候不需要?

这个想法是selectedClient 是应用程序的状态对象。

但是,它在每个组件中都带来了所有这些“订阅/取消订阅”,据我了解,如果您不取消订阅,您将向订阅数组添加另一个订阅,这意味着任何更改现在都会触发订阅下的代码两次。

应用程序是否应该有“selectedItem”的概念?

【问题讨论】:

    标签: angular rxjs angular2-routing observable


    【解决方案1】:

    你的设计看起来很扎实。你可能想考虑ngrx/store,他们也使用Observables / BehaviorSubjects,但另外实现了Redux模式,这提高了整体代码的可读性和设计。

    通常你不需要取消订阅 Observables,例如HTTP 可观察对象在返回值(或错误)后自行完成。

    当 Observables 未完成时需要取消订阅,例如 Observable.timer,或者如果从 routerService 检索参数。

    【讨论】:

    • 感谢您的回答。我现在明白什么时候退订了。我之前尝试过ngrx/store,虽然它似乎有几乎完全相同的模式,但它们暴露了一些我发现很难使用的令人困惑的API
    • 我建议您阅读有关 redux 模式的更多信息。 Dan abramov 在 egghead.io 上有很好的教程。接下来你可能想查看ngrx/example-app
    猜你喜欢
    • 2012-05-11
    • 2018-12-31
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多