2017-08-09 65 views
0

我定义了诸如以下我的路线:Angular2混编版网址获取当前url

const appRoutes: Routes = [ 
{ 
    path: 'auth', 
    component: AuthenticationComponent, 
}, 
{ 
    path: '', 
    component: HomeComponent, 
    canActivate:[AuthenticationGuard], 
    children:[ 
    { 
    path: 'list', 
    component: TaskListComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'create', 
    component: CreateTaskComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'profile', 
    component: ProfileComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'agreement', 
    component: UserAgreementComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    ] 

}, 

]; 

我浏览他们喜欢以下:

<nav class="mdl-navigation"> 
    <a class="mdl-navigation__link" href="#/list">List</a> 
    <a class="mdl-navigation__link" href="#/create">Create</a> 
    <a class="mdl-navigation__link" href="#/profile">Profile <span *ngIf="profileNotPresent" mdl-badge="Start"></span> </a> 
    <button class="mdl-button mdl-js-button" (click)="logout()"> 
     <i class="material-icons">exit_to_app</i> 
    </button> 
</nav> 

我不得不添加哈希,因为当我部署的应用程序它开始抛出我的路线404错误。随着哈希网址它的作品。

但是在我的代码我有我在那里显示的条件下,是真实的,如果它是基本路线股利的条件:

if(this.router.url == '/'){ 
    this.showHomeContent=true; 
} 

那个时候没有哈希我的网址是“/”,“/配置文件'等,它用来正确工作。现在他们是'#','#/ profile'等等,并且这个条件不再起作用,导致特定的div始终保持打开状态。

我该如何解决这个问题?

+0

只是添加散列工作? '==#/' – DeborahK

回答

1

您需要开始使用Angular路由器进行导航。我的意思是[routerLink]而不是href。如果没有#,你可能会得到404,如果你输入一个URL试图找到一个未知的资源。默认情况下,Angular使用PathLocationStrategy,在这种情况下发出服务器请求。

如果您要使用路由器导航,您可以通过配置重定向到index.html来解决此问题,然后路由器将正确导航。

因此,开始正常使用的路由器,而且您的应用模块中添加此:

providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}] 

路由器将被添加#-sign的网址,并不会作出导致服务器端请求404.但是,再次使用routerLink指令替换你的hrefs。

+0

我同意这一点,在角度应用程序内导航时,使用'routerLink'是必须的。 – Zze

0

它在文档还挺解释 - 如果使用PathLocationStrategy您必须提供APP_BASE_HREF或在您的index.html插入PathLocationStrategy

路由器支持两种策略PathLocationStrategyHashLocationStrategy

领导<base href="/">

这应该解决您的问题。