Angular2路由器错误:无法find主要sockets加载“主页”

我刚开始使用新的路由库(@ angular / router v3.0.0-alpha.7),但下面的官方文档导致错误如下:

browser_adapter.ts:74: EXCEPTION: Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'HomePage' 

问题是 – 我如何摆脱错误,使路由器按预期行事? 我错过了一个设置?

(使用alpha.6版本时出现相同的错误。)

app.component.ts

 import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES } from '@angular/router'; @Component({ selector: 'app', template: ` <p>Angular 2 is running...</p> <!-- Routed views go here --> <router-outlet></router-outlet> `, providers: [ROUTER_DIRECTIVES] }) export class AppComponent { } 

app.routes.ts

 import { provideRouter, RouterConfig } from '@angular/router'; import { HomePage } from './pages/home/home'; export const routes: RouterConfig = [ { path: '', component: HomePage } ]; export const APP_ROUTER_PROVIDERS = [ provideRouter(routes) ]; 

home.ts

 import { Component } from '@angular/core'; @Component({ template: '<h1>Home Page</h1>' }) export class HomePage { } 

main.ts

 /* Avoid: 'error TS2304: Cannot find name <type>' during compilation */ ///<reference path="../../typings/index.d.ts" /> import { bootstrap } from "@angular/platform-browser-dynamic"; import { APP_ROUTER_PROVIDERS } from './app.routes'; import { AppComponent } from "./app.component"; bootstrap(AppComponent, [ APP_ROUTER_PROVIDERS, ]).catch(err => console.error(err)); 

你的app.component.ts有一个错误看起来像你在providers数组中声明了一个指令。

 import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES } from '@angular/router'; @Component({ selector: 'app', template: ` <p>Angular 2 is running...</p> <!-- Routed views go here --> <router-outlet></router-outlet> `, directives: [ROUTER_DIRECTIVES] //here }) export class AppComponent { } 

虽然@ JS_astronauts已经提供了一个解决scheme,我认为这将是有益的解释错误…

当Angularparsing一个HTML模板并find指令RouterOutlet时 ,即findRouterOutlet的select器: <router-outlet></router-outlet>时,主要的出口被设置。

虽然你的模板确实包含<router-outlet></router-outlet> ,你的组件不包含directives: [ROUTER_DIRECTIVES] ,所以Angular不会查找任何由该常量定义的指令:

 export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive]; 

所以当AngularparsingAppComponent的HTML模板时,如果它不识别<router-outlet></router-outlet>那么它就会忽略它。 后来,当Angular尝试呈现默认路由组件(HomePage)时,它会抱怨,因为不知道该把它放在哪里。


如果您的元素select器中存在拼写错误,则也会发生此错误,例如:

 <roter-outlet></roter-outlet> 

在这种情况下,即使您的directives数组设置正确,Angular也不会find所需的<router-outlet>元素。

它应该是directives metadata而不是providers

 directives: [ROUTER_DIRECTIVES]