【问题标题】:Angular 4 not loading componentAngular 4不加载组件
【发布时间】:2017-11-20 11:38:20
【问题描述】:

我正在尝试在 Angular 4 应用程序中使用 Angular 路由,但该应用程序无法加载与请求的路由匹配的组件:

这里是app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts 看起来像这样:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.component.html:

<h1>
    Welcome to {{title}}!
</h1>
<router-outlet></router-outlet>

我的dashboard.component.html

<p>dashboard works!</p>

我试图找出问题所在,还查看了 Angular 4 Routing tutorial。请帮忙。

【问题讨论】:

  • import { AppRoutingModule } from './/app-routing.module'; Loot at ".//app.." 为什么是两个斜线?
  • 此导入由ng generate 在 app.module.ts 中添加。但是,它在删除一个斜线后尝试,没有工作。组件“AppComponent”未加载。
  • 您遇到的错误是什么?
  • 我查看了浏览器控制台,上面写着:Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document. at new PathLocationStrategy (common.js:647) at provideLocationStrategy (router.js:6995) at _callFactory (core.js:10651) at _createProviderInstance$1 (core.js:10599) at initNgModule (core.js:10549) at new NgModuleRef_ (core.js:11792) at createNgModuleRef (core.js:11782) at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:14092) at NgModuleFactory_.create (core.js:15216) at eval (core.js:5370)

标签: angular angular4-router


【解决方案1】:

我在一些故障排除后找到了解决方案,并在此link 上找到了答案。基本上,在app.module.ts 中,我们只需要添加这个import 语句来导入APP_BASE_HREF 令牌:

import { APP_BASE_HREF } from '@angular/common';

并将APP_BASE_HREF 添加到providers 数组中:

providers: [ {provide: APP_BASE_HREF, useValue: '/' }],

根据 Angular documentation 的另一种解决方案是简单地将 &lt;base href="/"&gt; 添加为 &lt;head&gt; 标记的第一个孩子。

【讨论】:

    【解决方案2】:

    我错了

    exports: [RouterModule] 
    

    您正在从 @angular/router 导出一个核心模块,因此您的 AppModule 由 RouterModule 扩展,而不是您的路由,而不是创建整个模块,只需导出 const 喜欢

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

    并在您的应用模块中导入路由

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 2018-03-04
      • 1970-01-01
      • 2019-09-09
      • 2017-11-12
      • 2018-02-08
      • 2018-12-21
      • 2018-06-01
      • 2017-12-03
      相关资源
      最近更新 更多