如何解决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方法,因此会有多个具有相同主题处理程序的订阅者,因此您的逻辑将执行多次。这会导致代码中行为不一致,并导致内存泄漏。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。