Yolomiys
Yolomiys

Reputation: 51

Merging an http request result with Array

I'm sorry about my confusing title but I basically have an Interface

export interface Tutor {
  name: string;
  rating: number;
  personalInfo: string;
}

And a function that Is getting a list of so-called Tutors from my back-end:

public loadTutors() {
    const url = 'http://localhost:8080/loadTutors';
    this.http.get<Tutor[]>(url).pipe(map(tutor =>
      tutor.forEach(tut => this.tutors.push(tut))))
      .subscribe();
    console.log(this.tutors);
  }

There are more fields in entity model of my back-end project then in Tutor Interface and adding a new Entity for only this specific request doesn't seem like a good scalable solution. After the function I get something like this:

Array(2)
0:
username: "Some Username"
email: null
name: null
password: "$2a$11$T44uetsjh1HxLu/ilsTiMODu.aoKLf8/zo3WPM/FUjeMXZRkpDz1S"
balance: 0
personalInfo: "Some personal Info"
rating: 0
userRoles: [{…}]
__proto__: Object
...

What would be the best practice of iterating through response fields or fitting the response to the Tutor Interface?

Thank you for your time and responses in advanced and I hope that you'll have a nice day!

Upvotes: 1

Views: 45

Answers (2)

AliF50
AliF50

Reputation: 18849

I would just pluck what I need.

I would do:

public loadTutors() {
    const url = 'http://localhost:8080/loadTutors';
    this.http.get<Tutor[]>(url).pipe(
        // pluck name, rating, personalInfo from backend response and return it as an object
        map(tutors => tutors.map(({ name, rating, personalInfo })=> ({ name, rating, personalInfo }))),
      )
      .subscribe(tutors => {
        console.log(tutors);
        this.tutors = tutors;
        console.log(this.tutors);
      });
  }

The non ES6 way to write the map would be

map(tutor => ({ name: tutor.name, rating: tutor.rating, personalInfo: tutor.personalInfo })

Upvotes: 1

Braulio David
Braulio David

Reputation: 113

The interface is just a model, it doesn't mean it convert the variables into that model, you have to do it manually. Then it is better to use the map function instead of pushing into the array. I also recommend you to run the console.log inside the subscribe because the http get method is asynchronous.

public loadTutors() {
    const url = 'http://localhost:8080/loadTutors';
    this.http.get<Tutor[]>(url).pipe(
      map(tutors => {
         this.tutors = tutors.map(tut => {
           return {
             name: tut.name,
             rating: tut.rating,
             personalInfo: tut.personalInfo
           }
         })
      })
    ).subscribe(() => {
       console.log(this.tutors)
    })

}

Upvotes: 1

Related Questions