繁体   English   中英

angular 7 Observable、Subject、Subscribe 不立即同步?

[英]angular 7 Observable, Subject, Subscribe not syncing immediately?

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

制作 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 function。 问题是当没有 [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ] 行时,personalInfoEditMode 值永远不会改变。 如果有行 [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ]personalInfoEditMode 值在 2 次点击后发生变化。 不是一键点击。

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

  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()
        }
      })
     
  }

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

原因在这里

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()
      }
   })
}

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

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

暂无
暂无

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

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