Michael Adlhoch
Michael Adlhoch

Reputation: 93

Angular Services: Promise returns strange results

I am struggling with designing Angular Services correctly. Use Case:

In an Angular Component I will call a service that should return the data I want to transform like so:

  private async getEntities() {
    
    let req = { condition1: this.condition1, condtion2: this.condition2 }
    let result = await this.EntityService.findByConditions(req);

  }

The corresponding service call looks as follows:

public findByConditions(requestBody) {
    return this.http.post<any>(API_URL + "/fancyEndpoint", requestBody).toPromise().then(response => 
                {console.log(response) }).catch(error => console.log(error));
 }

My Backend returns a List of these objects in a correct manner, but the result in the Frontend logs are as follows:

enter image description here

So since I am pretty new to Angular and Frontend developing I got following questions:

  1. How is it possible, that only one element is returned as the actual object and all others are represented by Database ids?
  2. What is the best practice for getting data that needs to be transformed before rendered (Example: Call Data from endpoint, build a ChartJs chart from this (we have to wait for the Observable/Promise to be completed), then render it to HTML)?

Sorry for the long question, I am new to Frontend developing and looking for best practice solutions.

Thanks in advance!

Upvotes: 1

Views: 42

Answers (1)

Stefan Morcodeanu
Stefan Morcodeanu

Reputation: 2158

you have 2 options here, one is to filter the data on the backend side based on params that you send in the body of the request, second options is you get all the data and then use pipe to filter out the data and return the data you need in UI, also you could make this pipe to receive params and to be more generic.

Here is a link about how to use pipes in Angular. https://angular.io/guide/pipes

More examples on how to use HTTPS module and hot to make calls to a backend here: https://angular.io/tutorial/toh-pt6

In 2 words pipes is like map or filter utils that you have in Javascript so the idea is before returning date to UI component you filter it.

a dummy example

1. getUserByAge()
2. getUserByLocation()

return this.service.getUsers().pipe( users => getUserByAge(users))

so here you pipe all the data to some utils functions and you filter for example user.age > 18 or using getUserByLocation you filter users only from US

Documentation is your friend so most of the time you'll find anything needed there.

Upvotes: 1

Related Questions