【发布时间】:2019-04-28 17:56:04
【问题描述】:
我是 Angular 新手,我想知道如何从 books.component.ts 中的方法加载不同的 home.component.html 文件。
这是我的books.component.ts 文件。
import { Component, OnInit } from '@angular/core';
import {BooksService} from '../books.service';
import {NgForm} from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-books',
templateUrl: './books.component.html',
styleUrls: ['./books.component.css']
})
export class BooksComponent {
constructor(private httpService: BooksService, private router:Router) {
}
status : any;
onSubmit(f: NgForm) {
console.log("AM I HERE AT LEAST");
this.httpService.checkLoginCred(f.value).subscribe(
data => {
// console.log(Object.values(data)[0]);
this.status = Object.values(data)[0];
if(this.status === "Successful"){
var path = "../home/home.component.html";
// console.log($location.path());
//console.log(this.router);
this.router.navigate(['/home']);
console.log("GREAT!");
}
return true;
}
);
}
}
我的app.module.ts 看起来像这样:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BooksComponent } from './books/books.component';
import { HomeComponent } from './home/home.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
@NgModule({
declarations: [
AppComponent,
BooksComponent,
HomeComponent,
],
imports: [
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
}
]),
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
我的books.component.ts 和books.component.html 文件在我的books 目录中。
我的home.component.ts 和home.component.html 文件在我的home 目录中
我附上了我的目录结构的截图。
到目前为止,我正在尝试使用 this.router.navigate,但我运气不佳。
任何帮助将不胜感激!
编辑
我的home.component.ts 文件如下所示:
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor() { }
}
【问题讨论】:
-
添加你的 home.component.ts ?我认为像 book.component.ts 一样,您可以在您的
templateUrls的@Component({})装饰器上直接在 home.component.ts 中添加您的主组件 html -
你的意思是把home.component.html放到home.component.ts的templateUrls中吗?
-
是的,当你使用 route.navigate 时会渲染组件 html
-
但是我的
home.component.ts中已经有了这个@Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }),但它仍然没有呈现home.component.html文件 -
好吧 - 最初加载哪个组件?预订?
标签: node.js angular typescript routing