当尝试
this.router.navigate(['newcard']);
时,它会正确加载 URL,但随后立即重定向到 localhost:4200/#。
这是我如何从 showcard 重定向到 newcard。
<a href="#" class="btn btn-primary" (click)="onCreateNew()">
<i class="bi bi-plus"></i>
</a>
onCreateNew(){
this.router.navigate(['newcard']);
}
newcard是运行
ng generate component newcard
默认生成的
这是我的app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NewcardComponent } from './newcard/newcard.component';
import { ShowcardsComponent } from './showcards/showcards.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{path: 'newcard', component:NewcardComponent},
{path: '', component:ShowcardsComponent},
{path: '**', component: PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: false })],
exports: [RouterModule]
})
export class AppRoutingModule { }
这是我的 app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule } from '@angular/common/http';
import { NewcardComponent } from './newcard/newcard.component';
import { ShowcardsComponent } from './showcards/showcards.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
@NgModule({
declarations: [
AppComponent,
NewcardComponent,
ShowcardsComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
从
href="#"
元素中删除 <a>
。相信单击链接时会导致另一个重定向。
<a class="btn btn-primary" (click)="onCreateNew()">
<i class="bi bi-plus"></i>
</a>
或者,您可以使用
[routerLink]
属性而不使用 click
事件。
<a class="btn btn-primary" [routerLink]="['newcard']">
<i class="bi bi-plus"></i>
</a>
据我所知,我想到的第一个问题是您的
<a>
标签,该标签旨在导航到 localhost:4200/newcard
。
您正在使用
href="#"
和 (click)="onCreateNew()"
,这是 2 个不同的路线,可能会产生错误,因为 href
首先被调用,之后路线不再匹配,因为它会打开 localhost:4200/#/newcard
或只是失败否则。
删除
href
标签中未使用的 <a>
属性,如下所示:
<a class="btn btn-primary" (click)="onCreateNew()">
<i class="bi bi-plus"></i>
</a>
我还建议您直接在模板中使用
[routerLink]
。 https://angular.io/api/router/RouterLink
<a class="btn btn-primary" [routerLink]="newcard">
<i class="bi bi-plus"></i>
</a>
希望这对您有帮助,如果您有更多问题,请联系我们!