DEV Community

Discussion on: Consuming APIs in Angular – The Model-Adapter Pattern

Collapse
 
marcel_cremer profile image
Marcel Cremer

Interesting approach to map the values to a typescript object. I currently use something like

class Person {
 firstname: string;
 lastname: string;
 age: number = 21;

 constructor(initialValues: Partial<Person>) {
  Object.assign(this, initialValues);
 }
}
...
 list(): Observable<Person[]> {
    const url = `${this.baseUrl}/`;
    return this.http.get(url).pipe(
      map((data: any[]) => data.map(item => new Person(item)),
    );
  }
...

to return the correct type and also be able to set default values in the class, but this doesn't decouple the code as nice as your Adapter. Might be worth a try, thank you :)

Collapse
 
florimondmanca profile image
Florimond Manca

Thanks for sharing your approach :) I also used it in some cases when I was sure the fields wouldn't change much; but as soon as they did, I had to resort to an adapter.

(Also, I've just learnt about TypeScript Partial, thank you ✌️)

Collapse
 
gabrieltaets profile image
Gabriel Taets

Just be careful with Object.assign() in that constructor. While you're telling Typescript that you'll be receiving a Partial as an argument, that is not validated in runtime. So you might have a Person object with more (or less) properties than expected, should your back-end misbehave for some reason.