I am trying to control the flow of components - some components cannot be accessed directly i.e must come from a previous component. e.g OrderDetails component must be completed and validated before you can access Payment component.
Can't stop a user entering "localhost:xxxxx/#/PaymentDetails"
How can I check the user has come from the OrderDetails component and has completed the form? I have tried below in the PaymentDetails component but doesn't work.
Any help guidance highly appreciated.
this.router.events
.filter(e => e instanceof RoutesRecognized)
.pairwise()
.subscribe((event: any[]) => {
console.log(event[0].urlAfterRedirects);
console.log(event[0]);
alert("PREVIOUS" +event[0].urlAfterRedirects);
});
this.router.events
.filter(event => event instanceof NavigationStart)
.pairwise()
.subscribe((value: [NavigationEnd, NavigationEnd]) => {
let previousUrl = value[0].url;
let nextUrl = value[1].url;
console.log(value);
alert("PR" + previousUrl);
alert("CR" + nextUrl);
});
You can use a CanActivate Routeguard to handle valid Routing to your PaymentDetailComponent. The components can communicate via a service and this service holds a state which has to be true to succesfully route to PaymentDetailsComponent.
For more details check the angular documentation
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { OrderDetailService } from './path/to/OrderDetailService';
@Injectable()
export class PaymentDetailsGuard implements CanActivate {
constructor(private ods: OrderDetailService,
private router: Router) {}
canActivate() {
// Check here if OrderDetailService holds valid data, e.g valid form
// otherwise navigate the user to your OrderDetailComponent
if (this.ods.validToProceedToPaymentDetails) {
return true
} else {
this.router.navigate(['/orderDetail'])
return false
}
}
}