我已经关注了Angular网站上的Heros教程。我在app-routing.module.ts
内添加了自定义路由的2个组件但是,一旦我设置了路由,当我访问其路由时,我的组件都没有Address或Auth加载。 app shell app.component加载它的HTML就好了,但我的组件没有。我在我的组件中添加了ngOnInit
,当我访问网址时 ,因为某些原因,我添加自定义路由后,我的组件无法正常工作。当我访问/address
或/auth
时,应用程序组件会触发,我会看到
INSIDE APP COMPONENT
在控制台中,但是我没有看到来自地址或auth组件的任何控制台日志。
app.module
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AddressComponent } from './address.component';
import { AuthComponent } from './auth.component';
@NgModule({
declarations: [
AppComponent,
AddressComponent,
AuthComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
APP-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddressComponent } from './address.component';
import { AuthComponent } from './auth.component';
const routes: Routes = [
{ path: '', redirectTo: '/address', pathMatch: 'full' },
{ path: 'address', component: AddressComponent },
{ path: 'auth', component: AuthComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
auth.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html'
})
export class AuthComponent implements OnInit{
ngOnInit(): void {
console.log("INSIDE APP COMPONENT");
}
}
auth.component.html
<div>
<h3>Authentication & Authorization Page </h3>
</div>
app.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
ngOnInit(): void {
console.log("INSIDE APP COMPONENT");
}
}
答案 0 :(得分:1)
您必须在<router-outlet></router-outlet>
中拥有app.component.html
,因为这是组件呈现的位置。