下面是一些相關的示例代碼:
subscribe(fromID, toID, updateQueryViaSubscription) {
const IM_SUBSCRIPTION_QUERY = gql`
subscription getIMsViaSubscription($fromID: String!, $toID: String!){
IMAdded(fromID:$fromID, toID: $toID){
id,
fromID,
toID,
msgText
}
}
`;
this.subscriptionObserver = this.props.client.subscribe({
query: IM_SUBSCRIPTION_QUERY,
variables: { fromID: this.fromID, toID: this.toID },
}).subscribe({
next(data) {
const newMsg = data.IMAdded;
updateQueryViaSubscription((previousResult) => {
// if it's our own mutation, we might get the subscription result
// after the mutation result.
if (isDuplicateIM(newMsg, previousResult.instant_message)) {
return previousResult;
}
// update returns a new "immutable" list with the new comment
// added to the front.
return update(
previousResult,
{
instant_message: {
$push: [newMsg],
},
}
);
});
},
error(err) {
console.error('err', err); },
});
}
你會發現,updateQueryViaSubscription
被傳遞給subscribe
作爲參數。在此處,它來自於我的應用程序:
//NOTE: NAME OF 2ND PROPERTY IN DATA OBJECT ("instant_message" in this example) MUST BE IDENTICAL TO NAME OF RESOLVER
//OTHERWISE DATA WILL NOT LOAD
const CreateIMPageWithDataAndMutations = graphql(GETIMS_QUERY, {
options({ toID }) {
const fromID = Meteor.userId();
return {
variables: { fromID: `${fromID}`, toID: `${toID}`}
};
}
,
props({ data: { loading, instant_message, updateQuery } }) {
//debugger;
return { loading, instant_message, updateQueryViaSubscription: updateQuery };
},
});
export default compose(
CreateIMPageWithMutations,
CreateIMPageWithDataAndMutations,
withApollo
)(CreateIM);
export { GETIMS_QUERY };
注意,函數updateQuery
被添加到組件的道具之前傳遞到阿波羅組件,並通過我的代碼updateQueryViaSubscription改名。
我的代碼調用subscribe
在componentDidMount
:
componentDidMount() {
const userIsLoggedIn = Meteor.userId() ? true : false;
const {toID, ApolloClientWithSubscribeEnabled} = this.props;
if (userIsLoggedIn && toID){
this.fromID = Meteor.userId();
this.toID = toID;
this.subscribe(this.fromID, this.toID, this.props.updateQueryViaSubscription);
}
}
...和取消在componentWillUnmount:
componentWillUnmount() {
if (this.subscriptionObserver) {
this.subscriptionObserver.unsubscribe();
}
}
我希望這個信息是有幫助的。