Home > database >  AWS-Amplify, How do I redirect to another URL after sign-in in angular?
AWS-Amplify, How do I redirect to another URL after sign-in in angular?

Time:05-17

I'm using the latest AWS-Amplify's authentication component. It can logged in successfully but after login I need to sent the route to another url which I can't able to achieve, it keeping the same url after logged in. BUT I need to set a custom url where it automatically redirect if a user login successfully.

Note : I'm not using aws-amplify-angular package I'm using these packages,

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

Also I checked this import {AuthenticatorService} from '@aws-amplify/ui-angular'; service but here I didn't find any response with observable type, I think that's why I don't get any event or something instantly after user login successfully. I need to route imminently after a successful login. So I need an event so that I can do that .

My main.ts :

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

auth.component.html : [ there is no code in ts ]

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

& the routes setup like this,

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

I didn't get any good solution with using this packages. Please help with this issue or am I missed something in my configuration .

CodePudding user response:

I didn't want to use aws-amplify-angular package but I need to because there is no good solution out there, without this package I tried to use angular hooks because when change detection runs I can get authenticated & unauthenticated states from AuthenticatorService which came from import { AuthenticatorService } from '@aws-amplify/ui-angular'; but using hooks (AfterContentChecked, AfterViewChecked) it works sometimes,sometimes not & sometimes occurred errors.

[ I did't use both hooks at a time, I tried separately]

So, Finally I need to install aws-amplify-angular for using the AmplifyService's & then I do this changes bellow,

 constructor(private router: Router, private amplifyService: AmplifyService) { }

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

Don't forget to add AmplifyService to put in providers array in app.module.ts.

  • Related