import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';import{Course}from'./course.model';import{Observable}from'rxjs';import{map}from'rxjs/operators';@Injectable({providedIn:'root'})exportclassCourseService{privateapiUrl='http://api.myapp.com/courses';constructor(privatereadonlyhttp:HttpClient){}list():Observable<Course[]>{returnthis.http.get<any[]>(this.apiUrl).pipe(// Adapt each item in the raw data arraymap(data=>data.map(Course.adapt)));}}
Do you see any of these approaches being better than another for some reason? They produce exactly the same result, but yours utilizes Angular's DI, mine does not.
It's a very clever alternative implementation of this pattern. I like how this approach binds the adaptation code to the model class. Also saves an import statement, and the DI boilerplate. :-) I'd definitely try this out in my next Angular projects!
I am using the above mentioned method in my current project. Now I'm stuck in one requirement where the value of one variable should change according to the some conditions .
example :-
export class Course {
constructor(
public id: number,
public code: string,
public name: string,
public created: Date,
) { }
static adapt(item: any): Course {
return new Course(
item.id,
item.code,
item.name,//Change the name to "john doe" if item.id=0 and item.code = john
new Date(item.created),
);
}
}
Is there any option for me to add a function which would perform this action?
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The company I work for, we use a static method to construct that instead of a service:
And then we can use it as follows:
Do you see any of these approaches being better than another for some reason? They produce exactly the same result, but yours utilizes Angular's DI, mine does not.
It's a very clever alternative implementation of this pattern. I like how this approach binds the adaptation code to the model class. Also saves an import statement, and the DI boilerplate. :-) I'd definitely try this out in my next Angular projects!
Indeed. Map statement reads really nicely. 👌
Hi Florimond Manca,
I am using the above mentioned method in my current project. Now I'm stuck in one requirement where the value of one variable should change according to the some conditions .
example :-
export class Course {
constructor(
public id: number,
public code: string,
public name: string,
public created: Date,
) { }
static adapt(item: any): Course {
return new Course(
item.id,
item.code,
item.name,//Change the name to "john doe" if item.id=0 and item.code = john
new Date(item.created),
);
}
}
Is there any option for me to add a function which would perform this action?