我正在尝试使用 ApolloGraphql 完成的订阅来刷新计数器。 它几乎可以正常工作,因为我可以在开发工具中看到以下来自服务器的事件数据:
{
"type": "subscription_data",
"id": 0,
"payload": {
"data": {
"dealVoteAdded": {
"voteCount": 16,
"__typename": "VoteType"
}
}
}
}
在此事件之前,计数器为 15。它应该变为 16,因为这是我得到的新值,但没有任何变化。视图永远不会刷新。为什么?
这是我的代码:
父组件
export class DealVoteComponent implements OnInit, OnDestroy {
public voteCount$;
private voteCounterSub$;
@Input() deal: Deal;
constructor(private dealService: DealService) { }
ngOnInit() {
/**
* Get update of dealVoteCount
*/
this.voteCount$ = this.dealService.getDealVote({
externalId: this.deal.externalId
})
.map(({data}) => {
console.log("voteCount$ data", data);
return data.getDealVote.voteCount;
})
/**
* Subscription of dealVoteCount
*/
this.voteCounterSub$ = this.dealService.dealVoteAdded({
externalId: this.deal.externalId
}).subscribe({
next: (data:any) => {
this.voteCount$.updateQuery(prev => {
const newCount = {
getDealVote: {
voteCount: data.dealVoteAdded.voteCount
}
};
return newCount;
});
},
error(err: any): void {
console.error('err', err);
}
})
}
ngOnDestroy() {
this.voteCounterSub$.unsubscribe();
}
}
看法
<dealtd-deal-vote-counter
[voteCount]="voteCount$ | async">
</dealtd-deal-vote-counter>
服务
@Injectable()
export class DealService {
constructor(private apollo: Apollo) { }
getDealVote(params) {
const params = {
query: getDealVote,
variables: variables
};
return this.apollo.watchQuery<any>(params);
}
dealVoteAdded(data) {
const params = {
query: dealVoteAdded,
variables: data
};
return getClient().subscribe(params);
}
}
图式
import gql from "graphql-tag";
export const VoteCountFragment = {
entry: gql`
fragment vote on VoteType {
voteCount
__typename
}
`
};
export const dealVoteAdded = gql`
subscription dealVoteAdded($externalId: String!) {
dealVoteAdded(externalId: $externalId) {
...vote
}
}
${VoteCountFragment.entry}
`;
export const getDealVote = gql`
query getDealVote($externalId: String!) {
getDealVote(externalId: $externalId) {
...vote
}
}
${VoteCountFragment.entry}
`;