2016-10-04 36 views
2

当试图通过输入url路径加载特定组件时,应用程序不加载组件。它只显示加载消息,并没有在控制台中提到任何错误。angular2在输入url路径时未加载组件

但是,如果我尝试加载相同的组件通过重定向的基础url到路径,然后一切工作正常,我重定向。

我不知道什么是造成这种奇怪的行为。我使用webpack2作为我的捆绑软件。

这是我的代码:

app.routes.ts

import { ModuleWithProviders } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 

import { LoginComponent } from './login/login.component'; 

const routes: Routes = [ 
    { path: 'login', component: LoginComponent }, 
    { path: '', redirectTo: '/processor', pathMatch: 'full' }, 
]; 

export const appRoutingProviders: any[] = [ 

]; 

export const routing: ModuleWithProviders = RouterModule.forRoot(routes); 

app.component.ts

import { Component, ViewContainerRef, ViewEncapsulation } from '@angular/core'; 

@Component({ 
    selector: 'app', 
    encapsulation: ViewEncapsulation.None, 
    template: ` 
     <router-outlet></router-outlet> 
    ` 
}) 
export class AppComponent { 
    private viewContainerRef: ViewContainerRef; 
    public constructor(viewContainerRef: ViewContainerRef) { 
     this.viewContainerRef = viewContainerRef; 
    } 
} 

app.module.ts

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 

import { routing, appRoutingProviders } from './app.routes'; 

import { AppComponent } from './app.component'; 
import { LoginComponent } from './login/login.component'; 

@NgModule({ 
    imports: [ 
     BrowserModule, FormsModule, HttpModule, routing 
    ], 
    declarations: [ 
     AppComponent, LoginComponent 
    ], 
    providers: [ appRoutingProviders ], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

的index.html

<html> 
    <head> 
     <meta charset=UTF-8> 
     <title>Hello World</title> 
     <link rel="icon" href="data:;base64,iVBORw0KGgo="> 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> 
     <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"> 
     <link href="global.css" rel="stylesheet"> 
     <base href="/"> 
    </head> 
    <body> 
     <app> 
      Loading ... 
     </app> 
    </body> 
</html> 

所以基本上,如果我加载http://localhost:3000/然后我得到我的LoginComponent内容显示出来,而URL被改变http://localhost:3000/login。但是,如果我从一开始试装http://localhost:3000/login比我没有得到“加载”旁边的任何味精定义中的index.html

回答

5

1)可以使用HashLocationStrategy(#)服务器端不需要配置路由

@NgModule({ 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    RouterModule.forRoot(routes, { useHash: true }) //<<<===here 
    ], 
    ... 
}) 

现在,如果刷新,您将能够看到相同的页面。

2)如果您正在使用pathLocationStrategy(/)服务器端路线需要配置其他清爽页面将不会带来同样的页面。

+0

谢谢你的作品! –