Angular 4未加载组件 [英] Angular 4 not loading component

查看:222
本文介绍了Angular 4未加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Angular Routes in Angular 4 app, but the app is not able to load the component matching the requested route:

这里是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:

app.component.html:

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

我的dashboard.component.html:

<p>dashboard works!</p>

我正在尝试找出问题所在,还查看了Angular 4路由教程.请帮忙.

I'm trying to figure out whats wrong, also looked at the Angular 4 Routing tutorial. Please help.

推荐答案

经过一些故障排除后,我找到了解决方案,并在此

I found the solution after some troubleshooting, and found the answer on this link. Basically, in app.module.ts, we just have to add this import statement for importing APP_BASE_HREF token:

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

并将APP_BASE_HREF添加到providers数组:

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

根据Angular 文档的另一种解决方案是简单地将<base href="/">添加为<head>标签的第一个孩子.

Another solution according to the Angular documentation is to simply add <base href="/"> as the first child of <head> tag.

这篇关于Angular 4未加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆