angular 7可观察,主题,订阅不立即同步?

问题描述

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

提供service.ts

import pandas as pd
 
df = pd.read_csv('ALL.csv',usecols=[1,2,3,4,5,6,7,8,9,10,11],header=None)
print(df)

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

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

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

解决方法

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

原因在这里

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方法,因此会有多个具有相同主题处理程序的订阅者,因此您的逻辑将执行多次。这会导致代码中行为不一致,并导致内存泄漏。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...