扩大 Graphql 订阅:在查询编辑器中工作,而不是在应用程序中工作

Amplify Graphql subscription: Works in query editor, not in app

我正在尝试设置一个基本的 graphQL 订阅,以便根据 Nader Dabit’s book and in this Medium post 中的食谱更新消息列表,但我的订阅永远不会在客户端中触发。奇怪的是,在 Amplify 的 Admin UI 的查询编辑器中,订阅按预期触发。然而,在应用程序中,它是蟋蟀。没有错误,什么都没有。

据我所知,我的版本唯一不寻常的地方是打字稿(以及 //@ts-ignore 需要说明 SDK 缺少 Observable 类型)。

正在创建消息:

  const handleMessageSubmit = async () => {
    try {
      const response = await API.graphql(
        graphqlOperation(mutations.createMessage, {
          input: {
            authorID: userState.person.id,
            text: message,
            messageGroupID,
          },
        }),
      );
    } catch (err) {
      console.log(err);
    }
  };

订阅:

 useEffect(() => {
    const subscription = API.graphql(
      graphqlOperation(subscriptions.onCreateMessage),
      // @ts-ignore
    ).subscribe({
      next: (event: any) => {
        console.log('new message:', event);
      },
      error: (error: any) => {
        console.log(error);
      },
    });

    return () => {
      console.log('unsubscribing');
      // @ts-ignore
      subscription.unsubscribe();
    };
  }, [messages]);

原来是我的导入有问题。

不正确:从“@aws-amplify/api”导入 API

正确:从“@aws-amplify”导入 { API }

不正确的 API 对于其他 graphQL 查询工作得很好,但订阅很无聊。

我还应该注意到,故障是在控制台中生成了一个 AWSAppSyncProvider.ts:204 Uncaught (in promise) undefined 错误,我之前没有注意到这一点,尽管这对找到解决方案没有太大帮助。