I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen:
Here is the service code snippet:
@Injectable({
providedIn: 'root',
})
export class UserService {
userOnChange: BehaviorSubject<User | null> = new BehaviorSubject<User | null>(null);
constructor(private api: HttpRequestService) {}
getCurrentUser() {
this.api.get<User>('/user/me', new HttpParams()).subscribe({
next: response => {
this.userOnChange.next(response.body);
},
});
}
}
And here's a snippet of the component code:
@Component({
selector: 'app-topbar',
templateUrl: './topbar.component.html',
styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent implements OnInit {
public user: User | null = new User();
constructor(
private authService: AuthService,
private router: Router,
public userService: UserService,
) {
this.userService.userOnChange.subscribe({
next: value => {
if (value != null) {
this.user = value as User;
console.log(value.Username);
console.log(this.user.Username);
}
},
});
}
ngOnInit(): void {
}
}
Lastly, here's a snippet of the template code:
<span *ngIf="this.user && this.user != null"> user: {{ this.user.Username }}</span>
However, I'm facing issues where the displayed value does not change on the template when the subject emits a new user. Additionally, both console.logs within the subscribe block write 'undefined'. Could you please help me identify what I might be doing wrong?