角度:带 id 的路由不起作用



我正在编写我的第一个 MEAN 堆栈,我得到了一个按钮,它必须跟随一个带有 id 的链接:

<a [routerLink]="['/bewerkProduct/', product._id]" *ngIf="username === product.createdBy"><button type="button" name="button" class="btn btn-sm btn-info">Bewerken</button></a>

这是我的路由模块:

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent} from './components/dashboard/dashboard.component';
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { ProfileComponent } from './components/profile/profile.component';
import { AuthGuard } from './guards/auth.guard';
import { NotAuthGuard } from './guards/notAuth.guard';
import { ProductComponent } from './components/product/product.component';
import { EditProductComponent } from './components/product/edit-product/edit-product.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard]},
{path: 'registreren', component: RegisterComponent, canActivate: [NotAuthGuard]},
{path: 'login', component: LoginComponent, canActivate: [NotAuthGuard]},
{path: 'profiel', component: ProfileComponent, canActivate: [AuthGuard]},
{path: 'producten', component: ProductComponent, canActivate: [AuthGuard]},
{path: 'bewerkProduct/:id', component: EditProductComponent, canActivate: [AuthGuard]},
{ path: '**', component: HomeComponent}
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(appRoutes)],
providers: [],
bootstrap: [],
exports: [RouterModule]
})

edit-product.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-edit-product',
templateUrl: './edit-product.component.html',
styleUrls: ['./edit-product.component.css']
})
export class EditProductComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

编辑产品组件.html

<p>
edit-product works!
</p>

当我单击该按钮时,它确实会路由到/bewerkProduct/5af158ae6cf6a701e0eb5bb0,但它不会打开 EditProductcomponent html。相反,它转到默认的HomeComponent。关于我在这里做错了什么的任何建议?

在 EditProductComponent 构造函数或 ngOnInit 方法中订阅路由参数。

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe((params) => {
const id: string =  params.id;
});
}

希望这有帮助。

相关内容

  • 没有找到相关文章

最新更新