I am using apollo-angular
+ subscriptions-transport-ws
in my project. I have the client setup to listen to the subscription for user's password updated or new user is created event. This is how it is setup
//Apollo Subscription
this.apollo.subscribe({
query: this.passwordUpdatedSubscription
}).subscribe(({passwordUpdated}:any) => {
return this.userDataQuery.updateQuery((previousResult) => {
let userIndex = previousResult.getUsers.findIndex(user => user.name === passwordUpdated.name);
let updatedUsers;
if (userIndex === -1) {
updatedUsers = [].concat(previousResult.getUsers).concat([passwordUpdated]);
} else {
updatedUsers = [].concat(previousResult.getUsers.slice(0, userIndex)).concat([passwordUpdated]);
if (userIndex !== previousResult.getUsers.length - 1) {
updatedUsers = updatedUsers.concat(previousResult.getUsers.slice(userIndex + 1));
}
}
return Object.assign({}, previousResult, {
getUsers: updatedUsers,
});
});
});
It seems to be working fine and does its job to notify the userDataQuery
about the update. In the userDataQuery
, it handles the updates this way
this.userDataQuery = this.apollo.watchQuery({
query: this.getUsersQuery
}).subscribe(({data}:any) => {
this.userData = data.getUsers;
// I have to call detectChanges to tell Angular to re-render the template.
// is there anyway to avoid doing this?
//this.ref.detectChanges();
});
The userData did get updated successfully, However, the changes is not reflected on the template. I will have to call this.ref.detectChanges();
to update the template.
The template is very simple
<span ng-if="userData">{{userData && userData[0] && userData[0].password}} </span>
Is there anything I am missing in the code. I thought the template should pick up the change automatically ?