Home > OS >  Implement conditional Routing in Angular
Implement conditional Routing in Angular

Time:04-05

I am trying to implement the following functionality. When a button is clicked to check a condition, condition should be a variable (or a sum in my case) different from undefined (if different then success). Then either go to the success-page if the condition is met or to display the fail page if the condition is not met ( if nothing was changed in the page just go to the success-page).

.html

<div >

<button type="button" (click)="updatePost()" routerLink="/success-page">Save</button>

The updatePost() method in the .ts file simply calls a function from the service and updates a user if some properties are changed (I have some input textboxes in the .html file).

updatePost() {
    this.sharedservice.updateUser(this.user).subscribe(response => {
}, error => {
    console.log(error);
    })
}

I tried many ways but the functionality is not correct. The problem might be the order in which I tried to call the function and implement the logic.

Both pages are registered as routes.

const routes: Routes = [
    {path: 'success-page', component: DisplaySuccessComponent},
    {path: 'fail-page', component: DisplayFailPageComponent},
];

CodePudding user response:

For that you should use Router from constructor. For that you need to provide constructor(private router: Router) {} then you need to check variable should not be undefined, null or not expected condition, then you need to route like this.router.navigate(['fail-page']); and if not undefined, not null and as expected condition then you can navigate by using this.router.navigate(['success-page']);. So, your final code like below:-

// In HTML:-

<button type="button" (click)="updatePost()">Save</button>

// In ts:-

updatePost() { 
    this.sharedservice.updateUser(this.user).subscribe(response => {
       this.router.navigate(['success-page']);
}, error => {
       this.router.navigate(['fail-page']);
    console.log(error);
    })
}

CodePudding user response:

you should not use routerLink in this case but navigate inside the upadtePost()function i.e:

updatePost() {
    this.sharedservice.updateUser(this.user).subscribe(
    response => {
        this.router.navigate('/success-page');
    }, 
    error => {
        console.log(error);
        this.router.navigate('/fail-page');
    });
}

  • Related