Angular 2不会从AppComponent移动到启动页面

时间:2017-12-01 19:32:16

标签: javascript angular web

我正在努力学习Angular 2并立即使用它。但我不知道为什么它不从AppComponent开始页面。只要我知道,这必须转移到测试页面并显示“测试”文本。但是当我运行它时,它只显示“Hello”,即app.component文本。如果我输入/ test url,则会出现404错误。这是因为测试组件未成功加载吗?

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 import { AppModule } from './app/app.module';
 platformBrowserDynamic().bootstrapModule(AppModule);

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { test } from './test';
@NgModule({
    imports: [
        BrowserModule,
        routing
    ],
    declarations: [
        AppComponent,
        test
    ],
    providers: [
    ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.routing.ts

 import { NgModule } from '@angular/core';
 import { Routes, RouterModule } from '@angular/router';
 import { test } from './test.index';
 const routes: Routes = [
     { path: '', component: test },
     { path: 'test', component: test },
     { path: '**', redirectTo: '' },
 ];

 export const routing = RouterModule.forRoot(routes);

app.component.ts

  import { Component } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: `<h1>Hello </h1>`,
    })
    export class AppComponent  {  }

test.ts

import { Component } from '@angular/core';

@Component({
    selector: 'test-app',
    template: `<h1>test </h1>`,
})
export class test {}

2 个答案:

答案 0 :(得分:0)

包含&#39; <router-outlet></router-outlet>&#39;在您的appcomponent模板中:

 <div>
      <h3>App component</h3>
    </div>
    <div>
      <router-outlet></router-outlet>
    </div>

答案 1 :(得分:0)

您似乎需要在<router-outlet></router-outlet>模板中提供app.component.ts

因此,未加载测试组件,因为如果没有<router-outlet>,它就无法将组件注入任何内容。

https://angular.io/tutorial/toh-pt5#add-routeroutlet