angular2 在进入 url 路径时不加载组件

angular2 not loading the component on entering the url path

当尝试通过输入特定组件的 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/ then I get my LoginComponent content displayed and the url is changed to http://localhost:3000/login. But I if try loading http://localhost:3000/login,除了 'loading' 消息定义 index.html

之外,我什么也得不到

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

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

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

2) 如果您使用 pathLocationStrategy(/), 服务器端路由需要配置否则刷新页面不会带来相同的页面。