Angular:带ID的路由不起作用

时间:2018-05-08 08:21:45

标签: angular mean-stack angular-routing

我正在编写我的第一个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]
  })

编辑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() {
  }

}

编辑product.component.html

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

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

1 个答案:

答案 0 :(得分:0)

在EditProductComponent构造函数或ngOnInit方法中订阅route params。

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {

}

ngOnInit() {
  this.route.params.subscribe((params) => {
    const id: string =  params.id;
  });
}

希望这有帮助。