无法在 Angular 4 中正确更改页面

Cannot change page properly in Angular 4

我正在尝试从主页(即 localhost.com)更改为另一个页面(localhost.com/listing)。该应用程序构建正常,但当我尝试更改页面时,没有任何反应。

我主要是遵循了教程,https://www.youtube.com/watch?v=L6ipgij-AUw

这是我的完整 app.module.ts 文件:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ListingsComponent } from './listings/listings.component';

@NgModule({
  declarations: [
    AppComponent,
    ListingsComponent 
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {
        path: 'listing',
        component: ListingsComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {

  btnClick = function () {
    this.router.navigate('/listing');
  };

}

我不确定 btnClick 功能是否在正确的位置。我得到了这个问答板的部分解决方案,但不确定它的位置是否正确。我已经通过使用检查了列表组件是否正常工作。它说 "listings works!" 但仍然从同一个主页这样做(理想情况下,这应该是一个带有 "listings works!" 的空白页面,例如没有导航栏)。

我应该如何正确地路由到新页面(即在 /listing 中没有主页的踪迹)?我不明白为什么会这样,因为 listings.component.html 不包含主页中的任何内容。

有关详细信息,请参阅:https://github.com/gf1721/directoryapp

改变

来自

 btnClick = function () {
   this.router.navigate('/listing');
};

btnClick () : void {
   this.router.navigate('/listing');
}

按钮也应该在组件上,你把它放在模块里面,无论如何都不起作用。

将按钮放在应用程序组件上并绑定逻辑以在按钮点击时导航,如上所述

根据您计划制作此应用程序的规模,您最好创建一个路由模块。

第 1 步:

这将在您的 src/app 文件夹中为您生成一个应用程序路由模块。

ng g m app-routing

第 2 步:

打开您的应用程序路由模块并导入您希望能够导航的所有组件以及路由器模块和路由。

import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent } from './dashboard/dashboard.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

步骤:3

在路由设置中添加常量:

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: 'dashboard', component: DashboardComponent},
  {path: 'login', component: LoginComponent},
];

步骤 4

将您的路由添加到导入中,然后导出路由器模块:

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  declarations: []
})

步骤 5

现在在您的模板 html 文件中,您可以执行以下操作:

<button type="button" routerLink="/home">Go home</button>
<router-outlet></router-outlet>

并且 "home" 上的内容会出现在 router-outlet 所在的位置。