Please help, I have a message service that is fetching my messages from the database and displaying them on a user profile page. When I create or delete a message, I can only see the changes when I refresh the browser.
The page updates dynamically before I apply a filter to sort by Id, why is the filter unbinding my array of messages?
profile component:
export class ProfileComponent implements OnInit {
user: User;
userId: any;
messages: any;
constructor(private authService: AuthService, private messageService: MessageService) {}
ngOnInit() {
this.authService.getUser().subscribe(
(user: User) => {
this.user = user;
this.userId = user.userId;
}
);
this.messageService.getMessages()
.subscribe(
(messages: Message[]) => {
this.messages = messages.filter(x => x.userId == this.userId);
//this.messages = messages; //this works perfect, but shows all users messages
}
);
}
}
Seems like your 1st API call(getUser method) is taking more time, it is getting finished after the getMessages method.
You should somehow make them dependent. You could convert getUser Observable to promise using toPromise method.
ngOnInit() {
this.authService.getUser()
.toPromise()
.then(
(user: User) => {
this.user = user;
this.userId = user.userId;
}
)
.then(() => {
this.messageService.getMessages()
.subscribe(
(messages: Message[]) => {
this.messages = messages.filter(x => x.userId == this.userId);
}
);
});
}
Change your code to this :
messages: Array<any> = [];
this.authService.getUser().subscribe(
(user: User) => {
this.user = user;
this.userId = user.userId;
this.messageService.getMessages()
.subscribe(
(messages: Message[]) => {
this.messages = messages.filter(x => x.userId === this.userId);
//this.messages = messages; //this works perfect, but shows all users messages
}
);
}
);
You just need to nest the other observables , so it will be called once the first finishes it calls.