Angular2 路由 - 手动 url 导航 [英] Angular2 routing - manual url navigation

查看:33
本文介绍了Angular2 路由 - 手动 url 导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的应用

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

<a [routerLink]="['/Test']">点击我</a><div class="main-container"><路由器插座></路由器插座>

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

@Component({选择器:'应用',templateUrl: 'app/app.component.html',指令:[HomeComponent、TestComponent、ROUTER_DIRECTICIVES]})@RouteConfig([{path: '/', 组件: HomeComponent, as: 'HomeComponent'},{path: '/test', 组件: TestComponent, as: 'Test'}])导出类 AppComponent { }

要导航到我的应用程序,请转到

http://localhost/app

效果很好,它按预期将我导航到我的主组件视图.当我点击点击我"按钮时,我被导航到

http://localhost/app/test

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

http://localhost/app/test

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

解决方案

在新的路由器规范中,您需要这样的东西:

router.navigateByUrl("/app");

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

I have a very simple app

My app.component.html looks like this:

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

My app.component.ts looks like this:

@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 { }

To navigate to my app, I go to

http://localhost/app

Which works perfect, it navigates me to my home component view as expected. When I click the "CLICK ME" button, I am navigated to

http://localhost/app/test

And my test component is rendered as expected... HOWEVER, if I manually navigate to

http://localhost/app/test

My home component is loaded instead of my test component...what gives? How can I set up routing so that manual navigation to the test url actually returns my test component's view in the router outlet? Is this possible? I don't want to go to the landing page every time...

解决方案

In the new router especification you need something like this:

router.navigateByUrl("/app");

or

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

这篇关于Angular2 路由 - 手动 url 导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆