角度导航功能不起作用。 URL发生更改,但未发生实际重定向

时间:2018-11-18 14:37:13

标签: angular angular6

我可以使用Angular 6导航功能来路由到网页。但是,尝试使用简单的导航来检查适用性,但是它不起作用。

以下是Angular版本和代码段。 URL在浏览器中发生了变化,但未发生实际重定向

Angular CLI: 6.2.7
Node: 8.12.0
OS: win32 x64
Angular: 6.1.10
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.8.7
@angular-devkit/build-angular     0.8.7
@angular-devkit/build-optimizer   0.8.7
@angular-devkit/build-webpack     0.8.7
@angular-devkit/core              0.8.7
@angular-devkit/schematics        0.8.7
@angular/cli                      6.2.7
@ngtools/webpack                  6.2.7
@schematics/angular               0.8.7
@schematics/update                0.8.7
rxjs                              6.2.2
typescript                        2.9.2
webpack                           4.16.4


/**** app.routing.ts *****/
import { RouterModule, Routes } from '@angular/router';
import { ListUserComponent } from "./list-user/list-user.component";
import { EditUserComponent } from "./edit-user/edit-user.component";


const routes: Routes = [
  {path: 'list-user', component: ListUserComponent },
  {path : 'edit-user', component : EditUserComponent}
];

export const routing = RouterModule.forRoot(routes);

/*********app.module.ts ******/
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { ListUserComponent } from './list-user/list-user.component';
import { EditUserComponent } from './edit-user/edit-user.component';

@NgModule({
  declarations: [
    AppComponent,
    ListUserComponent,
    EditUserComponent
  ],
  imports: [
    BrowserModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

/ ****列表用户组件**** /

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {

  constructor(private router:Router) {
    console.log('constructor of list user');
this.router.navigate(['/edit-user']);

  }

  ngOnInit() {


  }

}

URL更改为http://localhost:4200/edit-user。 但是不会显示“编辑用户”页面的内容。它停留在相同的“列表用户”页面上

1 个答案:

答案 0 :(得分:0)

很可能您没有在根组件模板中添加<router-outlet></router-outlet>。这就是告诉Angular Router需要在何处加载与特定路由相对应的组件模板的原因。

如果还没有这样做,请将<router-outlet></router-outlet>标记添加到app.component.html或要从中开始路由的任何组件。

这是您推荐的Sample StackBlitz