Thank you for the help first. Using Angular 7. What I'm trying to do is controlling one variable from several components,
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()
}
}
And imported service.ts to component.ts I made when there is a click event, it calls onChangeMode function. the problem is when there is no [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ] line, personalInfoEditMode value never changes. And if there is the line [ this.gpc.clickGeneralProfileController(this.personalInfoEditMode) ] personalInfoEditMode value changes after 2 clicks. Not one click.
I don't understand why it is not working. Plz, help. and let me know if there is more code needed for this question. Thanks!.
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()
}
})
}
The reason why you dont see any of changes immediate is pretty common problem.
The reason is here
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()
}
})
}
In this method you call the subscribe method of a simple subject. A subject only emits the new value to the currently subscribed elements. So when you call the clickGeneralProfileController() method it emits the value right away but since at that time of the emit there are no subscribers, you will not get anything for the first click.
Also since you call the subscribe method every time when the onChangeMode is called there will be several subscribers with the same handler to the subject so your logic will execute several time. This causes inconsistent behaviour in your code and also causing memory leak.