简体   繁体   中英

How do I code a redirect in an Angular page?

In my new Angular 8 app I have a page (technically route) where a user selects one of 3 pages to go to in a radio button choice and based on her selection, gets redirected to her selected page. I know other web technologies (php, Coldfusion) had a simple redirect call, but how would I do this using routes? (Since the route has to load within the application....)

I suspect the answer lies in calling a route from within my if/else/elseif block (that simply traverses the user's possible selections)

if (radio_select_1) 
{redirect to page 1}
elseif (radio_select_2) 
{redirect to page 2}
else (radio_select_3) 
{redirect to page 3}

Based on the selected radio button I would expect to redirect the user to that page in the app.

You need to import/inject the Router module . Once you have that, you can redirect a couple of different ways.

Example:

export class MyComponent {
    private _router: Router;
    constructor(_router: Router) {
        this._router = _router;
    }
    doRedirect(url): Promise<void> {
        await this._router.navigateByUrl(url);
    }

}

OR redirect directly in your router module

  {
    path: 'redirectroute',
    redirectTo: '/some/path',
    pathMatch: 'full'
  },

NOTE that url for the redirect needs to be a route . If it's an external url, unfortunately you're going to have to use window.location.href = url;

You may refer https://angular.io/guide/router or https://angular.io/tutorial/toh-pt5 to full fill your requirement. I guess you have put the inside your component. To simply answer the question you have to import the router module

    import { Router } from '@angular/router';
constructor( private router:Router) {
}
if (radio_select_1) 
{this.router.navigate(['page_1']);}
elseif (radio_select_2) 
{this.router.navigate(['page_2'])}
else (radio_select_3) 
{this.router.navigate(['page_3'])}

To do that you have to define the routes inside app.module.ts or in an imported route variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM