router.navigate没有导航到定义的路径html

时间:2018-04-05 05:22:39

标签: angular typescript routing

我是棱角分明的新人。创建从一个组件到其他组件的简单导航。使用router.navigate方法进行导航。

单击按钮时,url会更改,但该特定组件html页面未显示。

this.router.navigate(['登录']);

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { LoginComponent } from './Components/ProfileComponents/login/login.component';
import { Routes, RouterModule } from '@angular/router';
import { TestrouteComponent } from './testroute/testroute.component';


const appRoutes: Routes = [
  { path: 'login', component: TestrouteComponent }
];
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    TestrouteComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes, { enableTracing: true })
  ],
  exports: [RouterModule],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private router: Router, private _activateRoute: ActivatedRoute) {}
  title = 'app';
  testRouting() {
  this.router.navigate(['login']);
  }
}

app.component.html

<div style="text-align:center">
  <h1>
    Welcome
  </h1>
</div>
<h2>Here are some links to help you start: </h2>
<button (click)="testRouting()">test</button>

testroute.component.html

<p>
  testroute works!
</p>

testroute.component.ts

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

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

  constructor() { }

  ngOnInit() {
  }

}

普通代码只想检查router.navigate功能。不确定我到底错过了什么。

1 个答案:

答案 0 :(得分:1)

我认为您忘记在 /* 1 */ { "_id" : ObjectId("59fabc5ec85c3400123cdf5b"), "tasks" : [ { "name" : "Comprar champagne", "dueDate" : ISODate("2019-01-31T06:00:00.000Z"), "_id" : ObjectId("5a723e868dba4f0014c0c556"), "done" : true } ] } /* 2 */ { "_id" : ObjectId("5a1c99ccba7cc60014c99945"), "tasks" : [ { "name" : "Prova do vestido", "dueDate" : ISODate("2018-05-10T03:00:00.000Z"), "_id" : ObjectId("5a7336d5b882bc0014daeba9"), "done" : false } ] } 文件中添加<router-outlet></router-outlet>

当url匹配给定路由时,它将添加路由器模块中定义的组件。因此,在您的情况下,它会添加app.component.html

例如在您的app.component.html

TestrouteComponent

请注意,即使在设置html时路线发生变化,你的h1,h2,按钮元素仍然可见。