javascript - navigate 和 navigateByUrl 在 2.0.0-rc.1 上的 ngOnInit 中无法正常工作

标签 javascript angular angular2-routing

由于 2.0.0-rc.1 router.navigaterouter.navigateByUrl 似乎不再正常工作在 ngOnInit 中使用。

我没有收到任何错误或任何错误,但看起来 navigate 发生得太早了,因为紧接着它加载了 HomeComponent 并“替换”了LetterComponent 的内容。但是 URL 是正确的 (/letter)。

如果我将导航置于 1000 毫秒的 setTimeout 中,它会再次工作。

我需要使用不同的生命周期事件还是我做错了什么?或者这是一个错误?

请注意:通常指定导航位置的值来自 cookie(是动态的)。

这是我简化的应用程序组件:

@Component({
  selector: 'my-app',
  templateUrl: './app/app.component.html',
  directives: [ROUTER_DIRECTIVES]
})
@Routes([
  { path: '/', component: HomeComponent },
  { path: '/letter',component: LetterComponent },
  { path: '/cv', component: CVComponent },
  { path: '/attachment', component: AttachmentComponent }
])
export class AppComponent implements OnInit {

  constructor(private _router: Router) {
  }

  ngOnInit() {
      // todo: currently not working correctly (issue?)
      //also doesn't work: this._router.navigateByUrl("/letter");
      this._router.navigate(["/letter"]);
  }
}

Here's a demo发生的事情。 当我在没有路径的情况下访问应用程序时,它应该直接导航到 /letter “页面” - 正如您所看到的 URL 更改,但内容是错误的(内容是主页组件)。


更新:

这是我的导入,如果它们有任何相关性的话:

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

这是我的 Bootstrap :

import { bootstrap }  from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import {ROUTER_PROVIDERS} from '@angular/router';
import 'rxjs/Rx';

bootstrap(AppComponent, [
  ROUTER_PROVIDERS
]);

关于@eburgers 的帖子:

这是我做的:

import {Component} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router, ROUTER_PROVIDERS, OnActivate} from '@angular/router';
import {OnInit} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app/app.component.html',
  directives: [ROUTER_DIRECTIVES]
})
@Routes([
  { path: '/', component: HomeComponent },
  { path: '/letter',component: LetterComponent },
  { path: '/cv', component: CVComponent },
  { path: '/attachment', component: AttachmentComponent }
])
export class AppComponent implements OnActivate {

  constructor(private _router: Router) {
  }

  routerOnActivate() {
      // todo: currently not working correctly (issue?)
      //also doesn't work: this._router.navigateByUrl("/letter");
      this._router.navigate(["/letter"]);
  }
}

最佳答案

也许你应该这样做 setTimeout(() => this._router.navigate(["/letter"]), 0);

关于javascript - navigate 和 navigateByUrl 在 2.0.0-rc.1 上的 ngOnInit 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37293508/

相关文章:

javascript - 使用输入 "Id"而不是输入 "Name"

java - 如何获取具体日期?

url - 角度 2 : One path for multiple components?

Angular 路由不起作用。抛出错误的组件不是模块的一部分

php - 如何从 PHP 回显接收数据以使用 AJAX 显示?

javascript - 根据更改事件填充选择下拉列表

angular - 带有用户单击选定组件的动态选项卡

html - 基于路由的 Angular 子导航

angular - Angular2 中的 ViewProvider 和 Services 之间的区别?

angular - 在 Angular 中,我如何直接导航到延迟加载模块内的路径?