这个订阅有啥问题?我收到更新,但视图未刷新
Posted
技术标签:
【中文标题】这个订阅有啥问题?我收到更新,但视图未刷新【英文标题】:What's wrong with this subscription? I get updates but the view is not refreshed这个订阅有什么问题?我收到更新,但视图未刷新 【发布时间】:2017-08-23 12:40:59 【问题描述】:我正在尝试使用 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
`;
【问题讨论】:
【参考方案1】:使用apollo.subsribe
而不是getClient().subscribe
。
apollo.subsribe
扭曲 apollo 客户端订阅的角度区域。
【讨论】:
【参考方案2】:在这些情况下,我会在服务中使用可观察到的 BehaviorSubject
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
【讨论】:
以上是关于这个订阅有啥问题?我收到更新,但视图未刷新的主要内容,如果未能解决你的问题,请参考以下文章