我正在尝试将一个组件重定向到另一个组件(如页面重定向)
这是我的代码
应用-routing.module.ts
import { RoleComponent } from './role/role.component';
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/AppComponent', pathMatch: 'full' },
{ path: 'role', component: RoleComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
热门-header.component.html
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Verified</a>
</li>
<li class="nav-item">
<a routerLink="/role" class="nav-link" href="#">ROLES</a>
</li>
</ul>
AppComponent.html
<div class="container p-md-0">
<app-top-header></app-top-header>
<router-outlet></router-outlet>
<app-main-contain></app-main-contain>
</div>
答案 0 :(得分:2)
您可以使用Router类的router.navigate
功能。只需从@angular/router
导入路由器,然后在constructor(private router: Router)
中为其创建一个对象,然后使用router.navigate(['/roles']);
import { RoleComponent } from './role/role.component';
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/AppComponent', pathMatch: 'full' },
{ path: 'role', component: RoleComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {
constructor(private router: Router)
}
functionOnWhichRedirectShouldHappen(){
router.navigate(['/role']);
}
HTML
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Verified</a>
</li>
<li class="nav-item">
<button (click)="functionOnWhichRedirectShouldHappen()">ROLES</button>
</li>
</ul>
答案 1 :(得分:0)
尝试以下代码
您可以使用Angular $ window
$window.location.href = '/index.html';
控制器中的示例用法:
(function () {
'use strict';
angular
.module('app')
.controller('LoginCtrl', LoginCtrl);
LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];
function LoginCtrl($window, loginSrv, notify) {
/* jshint validthis:true */
var vm = this;
vm.validateUser = function () {
loginSrv.validateLogin(vm.username, vm.password).then(function (data) {
if (data.isValidUser) {
$window.location.href = '/index.html';
}
else
alert('Login incorrect');
});
}
}
})();
答案 2 :(得分:0)
您的 app-routing.module.ts 很好。现在,在您的组件中,您可以执行Import Router 并将其用于重定向。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() { }
redirect() {
this.router.navigate(['role']);
}
}
在您的component.html中,只需调用该redirect()
函数
<button (click)="redirect()"></button>
答案 3 :(得分:0)
只需将此路径添加到您的app-routing.module.ts
文件中,以便它可以知道该路径:
{ path: 'AppComponent', component: AppComponent }