我正在尝试使用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}
`;
答案 0 :(得分:0)
在这些情况下,我会在服务中使用BehaviorSubject observable
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
let bSubject = new BehaviorSubject(null);
getDealVote(params) {
const params = {
query: getDealVote,
variables: variables
};
bSubject.next(new value);
}
父组件中的
this.voteCount$ = this.dealService.bSubject
答案 1 :(得分:0)
使用Date: Mon, 26 Jun 2017 09:23:24 GMT
代替apollo.subsribe
。
getClient().subscribe
使用角度区域对apollo客户端subribe进行warp。