【问题标题】:angular 7 Observable, Subject, Subscribe not syncing immediately?angular 7 Observable、Subject、Subscribe 不立即同步?
【发布时间】:2020-08-11 18:21:36
【问题描述】:

首先感谢您的帮助。 使用 Angular 7。 我要做的是从多个组件中控制一个变量,

Made service.ts

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

@Injectable()
export class GeneralProfileControllerService {
  private subject = new Subject<boolean>()

  clickGeneralProfileController(value: boolean) { 
    this.subject.next(!value) 
  } 

  openGeneralProfileController() {
    this.subject.next(true)
  }

  closeGeneralProfileController() {
    this.subject.next(false)
  }

  getGeneralProfileController(): Observable<any> {
    return this.subject.asObservable()
  }
}

并将 service.ts 导入到 component.ts 我做了当有点击事件的时候,它调用了onChangeMode函数。 问题是当没有 [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ] 行时,personalInfoEditMode 值永远不会改变。 如果有这一行 [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ] 在点击 2 次后,personalInfoEditMode 值会发生变化。不是一键点击。

我不明白为什么它不起作用。请帮忙。让我知道这个问题是否需要更多代码。谢谢!。

  public onChangeMode(): void {
    console.log('node...')
    
    this.gpc.clickGeneralProfileController(this.personalInfoEditMode)
    
    this.subscription = this.gpc
      .getGeneralProfileController()
      .subscribe((value) => { 
        this.personalInfoEditMode = value 
        if (this.personalInfoEditMode) {
          this.initpersonalInfoForm()
        }
      })
     
  }

【问题讨论】:

  • 我不太确定你想要实现什么,但尝试交换this.gpc.clickGeneralProfileController(this.personalInfoEditMode)this.subscription = ... 的顺序。您在事件(主题)已经触发后订阅。您必须先订阅。

标签: angular observable angular7 subscribe


【解决方案1】:

您没有立即看到任何更改的原因是很常见的问题。

原因在这里

public onChangeMode(): void {
    console.log('node...')
    
    this.gpc.clickGeneralProfileController(this.personalInfoEditMode)
    
    this.subscription = this.gpc
     .getGeneralProfileController()
     .subscribe((value) => { 
      this.personalInfoEditMode = value 
      if (this.personalInfoEditMode) {
         this.initpersonalInfoForm()
      }
   })
}

在这个方法中你调用一个简单主题的订阅方法。主题仅向当前订阅的元素发出新值。因此,当您调用 clickGeneralProfileController() 方法时,它会立即发出值,但由于在发出时没有订阅者,所以第一次点击不会得到任何东西。

此外,由于每次调用 onChangeMode 时都会调用 subscribe 方法,因此会有多个订阅者对主题具有相同的处理程序,因此您的逻辑将执行多次。这会导致代码中的行为不一致并导致内存泄漏。

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多