AWS 放大认知 |刷新页面后配置中缺少区域

AWS Amplify Cognito | Missing region in config after I refresh page

我正在 Angular 中构建一个网络应用程序,使用 AWS 作为我的后端,并获得了我通过 Amplify 设置的 Cognito 运行。

在我的本地主机上的浏览器中登录到我的网络应用程序后,一切运行完美。

问题是,当我处理我的应用程序时,每次我进行更改并刷新浏览器时,我都会收到错误消息:

ConfigError: Missing region in config

自从我使用 Amplify 进行设置后,我不知道在哪里设置我的区域以及为什么这种情况一直发生。

我使用 authguard 来保护我的页面,因此只有 auth 用户才能看到除登录站点之外的所有内容。

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
try {
  let user = await Auth.currentAuthenticatedUser();
  console.log('Yes, Im authenticated', user);
  return true;
} catch (e) {
  console.log('Not authenticated ', e);
  this._router.navigate(['/login']);
  return false;
  }
 }
} 

我在这里有点头昏脑胀,在解决这个问题这么长时间后,我已经忘记了是什么,所以如果我需要提供更多代码或解释,我会很乐意这样做.

完整控制台错误:

ConfigError: Missing region in config
at Request.VALIDATE_REGION (http://localhost:4200/vendor.js:210527:45)
at Request.callListeners (http://localhost:4200/vendor.js:215956:20)
at callNextListener (http://localhost:4200/vendor.js:215946:12)
at http://localhost:4200/vendor.js:210521:9
at finish (http://localhost:4200/vendor.js:206617:7)
at Config.getCredentials (http://localhost:4200/vendor.js:206662:7)
at Request.VALIDATE_CREDENTIALS (http://localhost:4200/vendor.js:210516:26)
at Request.callListeners (http://localhost:4200/vendor.js:215952:18)
at Request.emit (http://localhost:4200/vendor.js:215928:10)
at Request.emit (http://localhost:4200/vendor.js:214552:14)

解决方案:

我使用 APP_INITIALIZER 在 加载组件之前获取我的区域,以解决此问题。

在我的供应商应用程序模块中,我添加了以下内容:

{
  provide: APP_INITIALIZER,
  useFactory: startupServiceFactory,
  multi: true
}

然后我在 /app 中添加了一个 ts 文件,内容如下:

import {Auth} from 'aws-amplify';
import * as AWS from 'aws-sdk';


export function startupServiceFactory() {
  return () => {
    return new Promise(async (resolve) => {
      const credentials = await Auth.currentCredentials();
      AWS.config.region = 'eu-central-1';
      AWS.config.credentials = Auth.essentialCredentials(credentials);
      resolve();
    });
  };
}

Link 到教程:

https://dzone.com/articles/how-to-use-the-app-initializer-token-to-hook-into