我学习Angular并遇到了一个小问题。如果我像这样将Component放入我的app.component.html中,就可以正常使用
<body>
<div class="container">
<app-search-books></app-search-books>
</div>
</body>
但是如果我这样配置app-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchBooksComponent } from './search-books/search-books.component';
const routes: Routes = [
{ path: 'search', component: SearchBooksComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
然后什么也没有发生。我想念什么?
这是文件夹search-books / search-books.component.ts中的search-books.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-search-books',
templateUrl: './search-books.component.html',
styleUrls: ['./search-books.component.scss']
})
export class SearchBooksComponent implements OnInit {
constructor() { }
ngOnInit() {
let isDone: boolean = false;
}
}
答案 0 :(得分:6)
将<app-search-books></app-search-books>
替换为<router-outlet></router-outlet>
注意:替换后,由于未定义根路由,将显示“空白”屏幕。
定义根路由
const routes: Routes = [
{ path: '', redirectTo: '/search', pathMatch: 'full'},
{ path: 'search', component: SearchBooksComponent }
];
此外,您还可以定义通配符路由,即,如果浏览任何不存在的页面,它将重定向到已定义的组件。
{ path: '**', redirectTo: '/search', pathMatch: 'full'}