我想使用Get参数使用id字段获取数据。以下是我的html网址代码,它重定向到特定页面,但未调用该服务以获取其余api
<a [routerLink]="['/usedCars/detail', lists.id]" class="btn btn-danger">Read more...</a>
下面是我的service.ts函数,我已经实现了import {HttpClient,HttpErrorResponse} from'@ angular / common / http';
getcarDetail(id:string){
return this.http.get<Autocardetail>(this.ServerUrl + 'autocardetail/'+id).pipe(
catchError(this.handleError)
);
}
下面是我在ngOninit函数上调用服务的我的component.ts文件。
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { Autocardetail } from '../autocardetail';
import { AutopostService } from '../autopost.service';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-autopostdetail',
templateUrl: './autopostdetail.component.html',
styleUrls: ['./autopostdetail.component.css']
})
export class AutopostdetailComponent implements OnInit {
detail$: Observable<Autocardetail>;
constructor(
private route: ActivatedRoute,
private router: Router,
private autopostService: AutopostService
) {}
ngOnInit() {
this.detail$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
return this.autopostService.getcarDetail(params.get('id'))
})
);
}
}
下面是我的班级文件
export class Autocardetail {
id: string;
car_name: string;
car_model: string;
car_built: string;
car_manufac_year: string;
}
下面是一个邮递员示例,响应的外观,
{
"car_id": "0",
"car_name": "Nissan",
"car_model": "Sunny",
"car_built": "Nissan inc",
"car_manufac_year": "2019",
"usedcarimages": [
"0_Nissan-1.jpg",
"0_Nissan-2.jpg"
]
}
当前-
switchMap((params: ParamMap) =>
this.autopostService.getcarDetail(params.get('id'))
)
如果使用箭头功能
,则与this.autopostService.getcarDetail(params.get('id'))
的代码指令swtichMap()
应在同一行;如果您要中断该行,则需要提及显式的return
语句。
switchMap((params: ParamMap) => {
return this.autopostService.getcarDetail(params.get('id'))
})
或
switchMap((params: ParamMap) => this.autopostService.getcarDetail(params.get('id')))