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

Angular 16集成Amplify Auth(Cognito):调用currentAuthenticatedUser报错

问题排查与解决方案

1. 修复重复且错误的初始化代码

你同时调用了Amplify.configure和Auth.configure,且Auth.configure的参数格式错误——它不需要把配置包在Auth键里,直接传入配置对象即可。重复配置会导致Amplify内部状态混乱,这是核心问题之一。

修改初始化代码为:

// 只需要调用一次Amplify.configure即可,无需再调用Auth.configure
Amplify.configure({
  Auth: env.cognito
});

2. 确保初始化时机正确

Angular 16对应用启动流程的时机要求更严格,务必在应用bootstrap之前完成Amplify配置。建议把配置代码放在main.ts的最顶部,示例:

import { Amplify } from 'aws-amplify';
import { env } from './environments/environment';

// 先配置Amplify
Amplify.configure({
  Auth: env.cognito
});

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

3. 解决Zone.js兼容问题

Angular 16使用的Zone.js 0.13.x和Amplify 5.x可能存在异步上下文兼容问题,导致Auth无法正确识别已认证状态。可以尝试在polyfills.ts中添加以下配置:

// polyfills.ts
(window as any).__Zone_disable_requestAnimationFrame = true;
(window as any).__Zone_disable_on_property = true;

或者在Amplify初始化时手动指定跳过Zone检测:

Amplify.configure({
  Auth: {
    ...env.cognito,
    clientMetadata: {
      skipZoneCheck: true
    }
  }
});

4. 验证配置完整性

检查你的Cognito配置语法是否完整,注意oauth对象的闭合(你提供的代码里oauth末尾缺少一个},如果实际代码也是如此会导致配置解析失败):

{
  region: 'eu-west-1',
  userPoolWebClientId: 'XXXXXXXXXXXXXXXXXXX',
  userPoolId: 'eu-west-1_XXXXXX',
  oauth: {
    domain: 'https://XXXXXX.auth.eu-west-1.amazoncognito.com',
    scope: ['openid', 'email', 'profile'],
    redirectSignIn: 'http://localhost:4200/',
    redirectSignOut: 'http://localhost:4200/login',
    responseType: 'code'
  } // 确保此处有闭合花括号
}

5. 清除缓存并重新测试

Angular 16的缓存机制可能保留旧配置状态,执行以下操作:

  • 清除浏览器缓存(Ctrl+Shift+Delete)
  • 删除node_modules和package-lock.json,重新执行npm install
  • 重启开发服务器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:40:53