Search code examples
angularangular-servicesangular-httpclient

How to send GET request to HTTP Client to retrieve data based on a parameter?


In my Angular app, I am able to send a HTTP GET request to a JSON-server & retrieve data from a JSON file.

Here is some of the code in my JobService at the moment:

getJob(id: number): Observable<IJob> {
    return this.httpClient.get<IJob>(`${this.baseUrl}/${id}`)
        .pipe(catchError(this.handleError));
}

getJobs(): Observable<IJob[]> {
    return this.httpClient.get<IJob[]>(this.baseUrl)
        .pipe(catchError(this.handleError));
}

And here is the IJob interface:

export interface IJob {
    id: number;
    title: string;
    description: string;
    employeeId?: number;
    managerId: string;
}

Here is my component code that calls the above methods:

loadExistingJobs() {
    this._jobService.getJobs().subscribe(
        (listJobs) => {
            this.jobs = listJobs;
        },
        (err) => console.log(err)
    );
}

getJob(id: number) {
    this._jobService.getJob(id).subscribe(
        (job: IJob) => {
            this.editJob(job);
            this.job = job;
        },
        (err) => console.log(err)
    );
}

Using the above code, I am able to retrieve all existing jobs & a specific job based on the jobId.

Now, I need to figure out how to retrieve all the jobs based on the managerId. I.e. I want to only display the jobs where the ManagerId = 1.

Can someone please tell me what needs to be done to do this?

Do I need to send a different GET request with a ManagerId parameter, or do I filter the data returned from getJobs?


Solution

  • If you need to implement separate API for getting Jobs Based on managerId you have to change your Backend API as well. But it can be achieved simply as follows. filter data which you got from getJobs API call based on managerId.

    filteredJobs: any;
    managerId: string = "1";
    
        loadExistingJobs() {
            this._jobService.getJobs().subscribe(
                (listJobs) => {
                    this.jobs = listJobs;
                    this.filteredJobs = this.jobs.filter(job => job.managerId === this.managerId);
                },
                (err) => console.log(err)
            );
        }