如何在 Angular 页面中编写重定向代码



在我的新 Angular 8 应用程序中,我有一个页面(技术路线(,用户在单选按钮选择中选择 3 个页面中的一个进行访问,并根据她的选择重定向到她选择的页面。我知道其他Web技术(php,Coldfusion(有一个简单的重定向调用,但是我如何使用路由来做到这一点?(由于路由必须在应用程序中加载...

我怀疑答案在于从我的 if/else/elseif 块中调用路由(它只是遍历用户的可能选择(

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

根据所选的单选按钮,我希望将用户重定向到应用程序中的该页面。

您需要导入/注入Router模块。一旦你有了它,你可以重定向几种不同的方式。

例:

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

直接在路由器模块中重定向

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

请注意,重定向的url必须是路由。如果它是一个外部 url,不幸的是,您将不得不使用window.location.href = url; <</p>

div class="one_answers">您可以

参考 https://angular.io/guide/router 或 https://angular.io/tutorial/toh-pt5to 完全满足您的要求。我想你已经把你的组件放在了里面。要简单地回答问题,您必须导入路由器模块

    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'])}

为此,您必须在 app.module.ts 中或导入的路由变量中定义路由。

最新更新