gpt4 book ai didi

javascript - 在 Angular 中使用 id 参数休息 api 调用

转载 作者:行者123 更新时间:2023-11-30 14:08:08 25 4
gpt4 key购买 nike

我有一个调用 rest api 的 Angular 应用程序,但是 rest api 数据是由哪个客户定义的:api/incident?customer_id=7 我将如何在 api 中反射(reflect)这一点网址或服务?和我的应用程序?我的服务如下:

    import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
providedIn: 'root'
})
export class

nowService {

serviceApiUrl: string = 'api/incident';

constructor(
private http: HttpClient,

) { }

getAll(): Observable<any> {
return this.http.get<any>(this.serviceApiUrl)
.pipe(
catchError(this.handleError)
);
}


private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)

} else {
console.log(error.status)
}
return throwError(
console.log('Something has happened; Api is not working!'));
};

}

component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import {HttpClientModule} from '@angular/common/http';
// Services
import { nowService } from '../../services/servicenow.service';
import { Incidents } from '../../models/incidents.model';


@Component({
selector: 'app-service-incident',
templateUrl: './service-incident.component.html',
styleUrls: ['./service-incident.component.scss']
})

export class ServiceIncidentComponent implements OnInit {

public incidents: any;
public loading = true;
public errorApi = false;

constructor(private service: nowService) {

}

ngOnInit() {
this.service.getAll().subscribe((data) => {
this.loading = true;
this.incidents = data.result;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}
}

所以是根据客户ID参数。我只是想知道如何做到这一点,因为我以前没有遇到过这个?

谢谢

最佳答案

代码可以如下:

   getAll(customerId): Observable<any> {
return this.http.get<any>(this.serviceApiUrl + "?customer_id" + customerId )
.pipe(
catchError(this.handleError)
);


ngOnInit() {
this.service.getAll(this.customerId).subscribe((data) => {
this.loading = true;
this.incidents = data.result;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}

或者你可以使用 HttpParams 类例子: https://angular.io/api/common/http/HttpParams

   getAll(customerId): Observable<any> {
const params = new HttpParams("customer_id", customerId)
return this.http.get<any>(this.serviceApiUrl ,{ params })
.pipe(catchError(this.handleError));

关于javascript - 在 Angular 中使用 id 参数休息 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com