我正在使用Angular 8,但页面上的路由遇到问题。我已经生成了所需的组件,并声明了它们并使用必要的路径导入它们,以便在网页上导航。
app.module.ts:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { RouterModule } from "@angular/router";
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { AngularFirestoreModule } from "@angular/fire/firestore";
import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component";
import { SignupComponent } from "./signup/signup.component";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { environment } from "src/environments/environment";
@NgModule({
declarations: [AppComponent, HomeComponent, LoginComponent, SignupComponent],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{ path: "", component: HomeComponent },
{ path: "login", component: LoginComponent },
{ path: "signup", component: SignupComponent }
]),
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestoreModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app-routing.module.ts:
import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component";
import { SignupComponent } from "./signup/signup.component";
const routes: Routes = [
{
path: "login",
component: LoginComponent
},
{
path: "home",
component: HomeComponent
},
{
path: "signup",
component: SignupComponent
},
{
path: "",
redirectTo: "/home",
pathMatch: "full"
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
由于我已将所有必要的组件添加到应用程序模块中,所以当我更改URL并添加/ login或/ signup时,它不应该工作吗?另外,我在组件中看不到我的html代码。 index.html是在我的网站上唯一可见并可以看到的地方。这与我的组件有关吗?
您的问题是您要在其他路由之前声明空路由。 Angular始终会将您发送到它匹配的第一个URL。对于您而言,{ path: "", component: HomeComponent }
是第一个匹配项,无论您尝试访问的URL是什么。
提示:尝试始终像以前一样使用RoutingModule,但不要导入RouterModule.forRoot(...)
。只需删除它就可以工作。