gpt4 book ai didi

Angular2 路由器错误 : cannot find primary outlet to load 'HomePage'

转载 作者:太空狗 更新时间:2023-10-29 16:45:35 26 4
gpt4 key购买 nike

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

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));

最佳答案

虽然@JS_astronauts 已经提供了解决方案,但我认为解释错误会很有启发性......

当 Angular 解析 HTML 模板并找到 directive RouterOutlet 时设置主导出。 ,即,当它找到 RouterOutlet 的选择器时:<router-outlet></router-outlet> .

尽管您的模板确实包含 <router-outlet></router-outlet> ,您的组件不包含 directives: [ROUTER_DIRECTIVES] ,因此 Angular 不会查找任何由该常量定义的指令:

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

所以当Angular解析AppComponent的HTML模板时,如果它不识别<router-outlet></router-outlet>所以它只是忽略它。稍后,当 Angular 尝试渲染默认路由组件 (HomePage) 时,它会提示,因为不知道将它放在哪里。


如果您的元素选择器中有拼写错误,也会发生此错误,例如:

<roter-outlet></roter-outlet>

在这种情况下,即使您的 directives数组设置正确,Angular 将永远找不到所需的 <router-outlet>元素。

关于Angular2 路由器错误 : cannot find primary outlet to load 'HomePage' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37950413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com