首页 文章

Angular2路由 - 手动网址导航

提问于
浏览
2

我有一个非常简单的应用程序

我的app.component.html看起来像这样:

<a [routerLink]="['/Test']">CLICK ME</a>
<div class="main-container">
    <router-outlet></router-outlet>
</div>

我的app.component.ts看起来像这样:

@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html',
    directives: [HomeComponent, TestComponent, ROUTER_DIRECTIVES]
})

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'HomeComponent'},
  {path: '/test', component: TestComponent, as: 'Test'}
])

export class AppComponent { }

要导航到我的应用程序,我会去

http://localhost/app

哪个工作完美,它按预期导航到我的主组件视图 . 当我点击“点击我”按钮时,我被导航到

http://localhost/app/test

并且我的测试组件按预期呈现...但是,如果我手动导航到

http://localhost/app/test

我的主组件被加载而不是我的测试组件......是什么给出的?如何设置路由,以便手动导航到测试URL实际上在路由器插座中返回我的测试组件的视图?这可能吗?我不想每次都去着陆页...

3 回答

  • 0

    在新的路由器especification中你需要这样的东西:

    router.navigateByUrl("/app");
    

    要么

    router.navigate(['HomeComponent'], {relativeTo: route});
    
  • 1

    这可能是由于服务器迁移造成的 . 对于上下文之后的任何错误路径或路径,您的服务器可能会重定向到 index.html .

    您应该将服务器配置为重写路径而不是重定向 .

    提供有关正在使用的服务器代码和服务器的更多信

  • 0

    已解决 - 我的引导程序缺少一些内容......我有

    bootstrap(AppComponent, [
      ROUTER_BINDINGS,
      bind(APP_BASE_HREF).toValue(location.pathname),
      bind(LocationStrategy).toClass(PathLocationStrategy )
      ]);
    

    但这是不正确的,手动输入:

    bootstrap(AppComponent, [
      ROUTER_BINDINGS,
      bind(APP_BASE_HREF).toValue("/"),
      bind(LocationStrategy).toClass(PathLocationStrategy )
      ]);
    

    似乎工作 . 感谢大家的帮助!

相关问题