AWS Amplify,在angular登录后如何重定向到另一个URL



我使用的是最新的AWS Amplify的身份验证组件。它可以成功登录,但登录后我需要将路由发送到另一个我无法实现的url,它在登录后保持相同的url。但我需要设置一个自定义url,如果用户成功登录,它会自动重定向。

注意:我没有使用aws-amplify-angular包我使用的是这些包,

"@aws-amplify/ui-angular": "^2.4.4", 
"aws-amplify": "^4.3.21",

我也检查了这个import {AuthenticatorService} from '@aws-amplify/ui-angular';服务,但在这里我没有发现任何可观察类型的响应,我想这就是为什么我在用户成功登录后没有立即收到任何事件或其他东西的原因。我需要在成功登录后立即进行路由。所以我需要一个活动,这样我才能做到。

我的main.ts:

import { Amplify } from 'aws-amplify'
import awsmobile from './aws-exports'
Amplify.configure(awsmobile)

auth.component.html:[ts]中没有代码

<amplify-authenticator [signUpAttributes]="['email']"></amplify-authenticator>

&这样设置的路线,

const routes: Routes = [
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'auth',
component: AuthComponent
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
];

使用这些软件包我没有得到任何好的解决方案。请帮助解决此问题,或者我的配置中遗漏了什么。

@aws-amplify/ui-angular最新版本的AuthenticatorService导入中,您可以订阅和侦听经过身份验证、取消身份验证和配置的authStatus,如果您从ngOnInitconstructor侦听,则可以等待必要的状态来进行重定向。

它也适用于签出

constructor(public amplifyService: AuthenticatorService, public router: Router) {
this.amplifyService = amplifyService;
amplifyService.subscribe((data: any) => {
if (data.authStatus === "authenticated") {
this.router.navigate(['/home']);
};
})
}
ngOnInit(): void {
}

要进行注销,您只需在导航栏中使用此功能

logOut() {
this.amplifyService.signOut()
this.router.navigate(['/login']);
}

通过这种方式,您可以维护最新版本的aws放大包,而不会因为编译过时的包或与其他aws包冲突的包而出现错误或失败。

我不想使用aws-amplify-angular包,但我需要使用,因为没有好的解决方案,如果没有这个包,我尝试使用角度挂钩,因为当运行更改检测时,我可以获得authenticated&unauthenticatedimport { AuthenticatorService } from '@aws-amplify/ui-angular';来的AuthenticatorService状态,但使用钩子(AfterContentCheckedAfterViewChecked)有时工作,有时不工作;有时会出现错误。

[我没有同时使用两个挂钩,我分别尝试过]

因此,最后我需要安装aws-amplify-angular以使用AmplifyService的&然后我在下面更改,

constructor(private router: Router, private amplifyService: AmplifyService) { }
ngOnInit() {
this.amplifyService.authStateChange$.subscribe(({state, user}) => {
if (state === 'signedIn') {
this.router.navigate(['/home'])
}
})
}

不要忘记添加AmplifyService以放入app.module.ts中的提供者数组。

import { Hub } from 'aws-amplify';
ngOnInit() {
// Used for listening to login events
Hub.listen('auth', ({ payload: { event, data } }) => {
if (event === 'signIn') {
const { signInUserSession = {} } = data;
const { accessToken = {} } = signInUserSession;
const { jwtToken, payload = {} } = accessToken;
const { 'cognito:groups': roles, username, exp } = payload;
localStorage.setItem('accessToken', jwtToken);
const payloadToSave = {
Role: roles[0],
Username: username,
exp,
};
localStorage.setItem('payload', JSON.stringify(payloadToSave));
this.zone.run(() => this.router.navigate(['/dashboard']));
} else {
console.log('Hide loader');
}
});
//currentAuthenticatedUser: when user comes to login page again
Auth.currentAuthenticatedUser()
.then(() => {
this.router.navigate(['/dashboard'], { replaceUrl: true });
})
.catch(err => {
console.log(err);
});
}

最新更新