如何在angular 7的激活链接中获取url参数,并从服务类中调用rest api

问题描述 投票:1回答:1

我想使用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"
    ]
}

我正在使用此网站作为参考https://www.truecodex.com/course/angular-project-training/service-and-http-client-for-blog-detail-recent-blog-and-categories-angular

json angular typescript angular-ui-router angular7
1个回答
1
投票

当前-

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')))
© www.soinside.com 2019 - 2024. All rights reserved.