Issue
I am new to Angular. I have a service class which has Subject event which is triggered from component A. Then I am redirected automatically to component B to subscribe to this event and extract its information to local variables. The result - They are undefined outside the scope of .subscribe() method.
This is the code in component B
ngOnInit(): void {
this.editUserForm = this.formBuilder.group({
userName: ['Enter username'],
firstname: ['Enter first name'],
lastname: ['Enter last name'],
email: ['Enter email']
})
this.userService.getEditUserInfoEvent().subscribe({
next:((editUserInfo) =>
this.setEditFormEventValues(editUserInfo))
})
}
private setEditFormEventValues(userInfo: IGetUserModel) {
this.id = userInfo.id;
this.editUserForm.patchValue({
userName: userInfo.userName,
firstname: userInfo.firstname,
lastname: userInfo.lastname,
email: userInfo.email
})
}
Is this the normal behavior and how can I extract the data, effectively? If I try to read the data of this.id outside these 2 methods - it is undefined Somewhere I read about the .map method but I am not sure how to implement it, exactly? Any help will be appreciated - more than 5 hours I am trying to solve this problem.
Solution
Okay guys. I've found my mistake. The mistake was that by event as a type was Subject. And that's the whole problem. When I send the event with Subject, the listeners are in another component and yet to be constructed. When a Subject does not have real listeners the event is disregarded. That's why I changed to behavior subject. It caches the last event and sends it when a subscriber is actively listening. Thank you for your cooperation.
Answered By - Andrеw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.