Home > Enterprise >  Is there anything wrong using the HttpClient in programmer defined classes in Angular?
Is there anything wrong using the HttpClient in programmer defined classes in Angular?

Time:03-30

I wonder whether I could use the provided HttpClient in my classes. For example, should we avoid this:

export class Order {
    constructor(private http: HttpClient,...){...}
    save(){
        return this.http.post(...)
    }
}

Could we do this or should we avoid it?

CodePudding user response:

Yes, it's doable what you are asking. But think about if you should do it.

Each time class is used, a new HttpClient is constructed, using more memory and adding more complexity to your code.

How would you pass params if for some you should need to give them to httpClient? E.g the url, headers etc. You would end up refactoring the class, and then refactoring every part that uses that class.

I would not use this approach. However, if for some specific case, this class is short lived and the object (or the function) will perform specific set of actions then yes, this would be one way to do it without creating a specific service for it.

Prefer Dependency Injection if possible (the use of services for http calls).

  • Related