You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Amplify与Angular集成:订阅功能无法正常工作问题求助

AWS Amplify Angular 订阅功能失效问题解决

按照AWS Amplify Angular入门教程集成时,OnCreateRestaurantListener订阅功能出现异常:

  • 不传参数时,报错:"Connection failed: { "errors":[{ "message":"Validation error of type UndefinedVariable: variable not found" }]}"
  • 传入空对象{}后错误消失,但创建新Restaurant时页面无法实时更新,需刷新才能看到新数据。

解决步骤

1. 传递正确的订阅参数

Amplify API更新后,订阅方法要求必须传入filter参数(即使是匹配所有数据的空过滤规则),调用时需传入包含filter的对象:

this.api.OnCreateRestaurantListener({ filter: {} })

2. 用NgZone触发Angular变更检测

Amplify的WebSocket订阅回调默认运行在Angular Zone之外,导致数据更新后视图无法自动刷新。需要使用NgZone将更新逻辑包裹,强制触发变更检测:

实现细节:

  • 导入并注入NgZone:
import { NgZone, Subscription } from '@angular/core';

// ...

constructor(private api: APIService, private zone: NgZone) {}
  • 修改订阅逻辑:
async ngOnInit() {
  this.api.ListRestaurants().then((event) => {
    this.restaurants = event.items as Restaurant[];
  });

  this.subscription = this.api.OnCreateRestaurantListener({ filter: {} }).subscribe((event: any) => {
    this.zone.run(() => {
      const newRestaurant = event.value.data.onCreateRestaurant;
      this.restaurants = [newRestaurant, ...this.restaurants];
    });
  }) as Subscription;
}

3. 组件销毁时取消订阅(推荐)

避免内存泄漏,在组件销毁生命周期中取消订阅:

ngOnDestroy() {
  this.subscription?.unsubscribe();
}

额外检查项

  • 确认GraphQL Schema中OnCreateRestaurant的订阅权限配置正确,确保当前用户有权限接收订阅事件。
  • 验证Amplify配置文件(aws-exports.js)中的AppSync端点、区域等信息准确无误。

内容的提问来源于stack exchange,提问作者Bruno Thiago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:48:15