【发布时间】:2019-11-19 23:02:13
【问题描述】:
我有一个带有汽车表的应用程序:
这是我的代码:
Carcomponent.html
<tbody>
<tr *ngFor="let car of allCars; index as carId" \>
<td [routerLink]="['/cars', carId]">{{car.carId}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
<td>{{car.color}}</td>
<td>{{car.topSpeed }}</td>
</tr>
</tbody>
我已经注册了这样的路线:
{ path: 'cars/:carId', component: CardetailsComponent }
这是我的 CarDetails.ts 文件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CarVM } from '../viewmodels/car-vm';
import { CarService } from '../services/car.service';
@Component({
selector: 'app-cardetails',
templateUrl: './cardetails.component.html',
styleUrls: ['./cardetails.component.css']
})
export class CardetailsComponent implements OnInit {
car: any;
carList: any;
constructor(private route: ActivatedRoute, private carservice: CarService) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.car = params.get('carId');
});
}
getCarList() {
this.carList = new CarVM();
this.carservice.getCarById(this.carList.carId).subscribe((res: any) => {
this.carList = res.data;
console.log(this.carList)
})
}
}
在我的 Cardetails.html 上,我想像这样显示所选的汽车:
<h2>Car Details</h2>
<div *ngIf="car">
<h3>{{ car.brand }}</h3>
<h4>{{ car.model }}</h4>
<p>{{ car.color }}</p>
</div>
路由工作正常,取车工作正常。现在我想选择一辆汽车,然后在下一页查看品牌、型号、颜色。我为此使用了视图模型:
export class CarVM {
CarId: number;
Brand: string;
Model: string;
Color: string;
TopSpeed: number;
}
如何在下一页看到所选的汽车?
我已按照本教程进行操作:
【问题讨论】:
-
Console.log
this.car变量在 CardetailsComponent 中得到了什么? -
carId是否等于index?如果没有,试试这个:<td [routerLink]="['/cars', car.carId]">{{car.carId}}</td> -
@shadowman_93 我得到 undefined
-
@dallows 当我使用您的解决方案时,我得到了正确的 carId,如下所示:localhost:4200/cars/445 我仍然没有得到 品牌、型号、颜色
-
在您的代码中,您试图访问属性
445的CarVM类女巫不存在。如果CarVM真的是一个数组,那么你应该使用this.car = CarVM.find(car => car.carId === params.get('carId'))
标签: javascript html angular typescript routing