0

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?

2
  • 1
    Generally, we use the service to handle get and post requests data. Service is a piece of reusable code with a focused purpose. A code that you will use across multiple components in your application. Commented Mar 29, 2022 at 7:34
  • @SainPradeep Yes, I am using services but I wondered whether one could do what I did above since each class would have its own specified post and get requests which they can use and if data is shared among classes I could put the requests for that in services Commented Mar 29, 2022 at 7:36

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.