几秒后,Angular 2自动路由

时间:2017-09-15 13:32:34

标签: angular routing angular2-routing

我怎样才能在2000毫秒内从app组件html导航到另一个组件html而不点击任何东西。我尝试过使用router.navigate方法,但它没有工作。它只停留在app组件html中。 App component.ts

   import { Component ,OnInit} from '@angular/core';
import {RouterModule,Router} from '@angular/router';
import { SecondComponent } from './second/second.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

})
export class AppComponent {

constructor(private router: Router){}

  ngAfterViewInit() {
 setTimeout(() => {
    this.router.navigate(["/second"]);
 }, 2000);
}
    }
    import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { SecondComponent } from './second/second.component';
import {RouterModule,Router,Routes} from '@angular/router'
const appRoutes: Routes = [
  { path: 'second', component: SecondComponent },

];
@NgModule({
  declarations: [
    AppComponent,
    SecondComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    ],
 bootstrap: [AppComponent]
})
export class AppModule {
}

App component.html:

<div class="my-container">
   <h3 id ="h31">Digit</h3>
</div>


 <router-outlet></router-outlet>

secondpage component.html:我希望在2秒后重定向到此页面

<div class="my-container">

<h3>Insurance made simple</h3>

<button type="button" class="btn btn-warning">Lets get started</button>

</div>

2 个答案:

答案 0 :(得分:0)

基本上,您要做的是,使用setTimout启动计时器并在完成时调用函数:

setTimeout(() => {
    this.router.navigate(["foo"]);
}, 2000);

答案 1 :(得分:0)

请使用

setTimeout(() => {
    this.router.navigate(["foo"]);
}, 2000);

在组件中的生命周期钩ngAfterViewInit()中,

ngAfterViewInit() {
 setTimeout(() => {
    this.router.navigate(["foo"]);
 }, 2000);
}

看看这是否解决了您的问题。

<强>更新

修改您的AppComponent以实施AfterViewInit lifeCycle hook / interface,

import { AfterViewInit } from '@angular/core';

export class AppComponent implements AfterViewInit {

<强> UPDATE_2:

理想情况下,如果您不想在路由app.component.html中显示当前SecondComponent的内容,那么您应该为其创建另一个组件(例如DefaultComponent) ,将<router-outlet></router-outlet>以外的模板的其余部分从app.component.html移动到DefaultComponent的模板,并通过设置新路径(对于DefaultComponent)和默认路径将其作为默认路径路径(到新路径):

const appRoutes: Routes = [
 { path: '', redirectTo: '/default', pathMatch: 'full' },
 { path: 'default', component: DefaultComponent },
 { path: 'second', component: SecondComponent },
];
  

app.component.html

<router-outlet></router-outlet> <!-- Move the rest of the html present here to the DefaultComponent -->