DEV Community

loading...

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

Collapse
amineamami profile image
amineamami • Edited

The http methods take an optional generic type so get<Course>(url) , this renders your adapter useless :

list(): Observable<Course[]> {
const url = "${this.baseUrl}/";
return this.http.get<Course>(url);
}

Collapse
florimondmanca profile image
Florimond Manca Author

Interesting point. I never thought that the generic type you could pass to .get(), .post(), etc, could be used by Angular to perform the conversion. Do you have examples of that being used?

The case for adapters is also handling complex conversions, such as building nested objects and the like. For example, what if GET: /courses/ returned course objects with a students field, representing a list of Student objects? Can generic type conversion handle that?

Also, how can generic type conversion decide to build a Date object out of the created field (a string)?

Happy to discuss further. :)

Collapse
amineamami profile image
amineamami • Edited

That code snippet works like a charm i’m using it currently it been like that since angular 5 or 4 not sure, your right about the date thingy but if you send it from backend as a date type. You’ll get it as a date type too in angular.

Thread Thread
florimondmanca profile image
Florimond Manca Author

Cool! Glad to hear simple type conversions work.

To my knowledge there is no Date type in JSON, though, so that still means the model-adapter pattern is needed in more complex use cases.

Thread Thread
amineamami profile image
amineamami

In typescript/JavaScript there is obviously, you’ll access it like a normal property Obj.dateProperty

Collapse
avronyc profile image
4lv4r0 • Edited

the generic type you are able to pass to an http get or post, etc... its merely to allow typed responses. The adapter is still needed if your model objects contain any methods, etc. So for instance if you have a method such a getFullName() within your User model, this wont be available for the objects returned by http.get. its still necessary to do a map in order to actually create the User objects based on the data received. Hope this clarifies a bit

angular.io/guide/http#requesting-a...

Forem Open with the Forem app