-
Notifications
You must be signed in to change notification settings - Fork 2
Home
In this application, I've used HttpClient
's methods - get, post, put and delete to perform CRUD operations on the mock json data which is run locally with json-server at http://localhost:3000/users
In Angular application, it is always a best practice to separate data presentation logic usually written in a Component and data access logic written in a Service.
Services are available to all classes and could be injected in any class throughout our application. Hence, it is good to write the data access logic in a Service (shown below)
getUsers(): Observable<User> {
return this.http.get<User>(this.url);
}
postUsers(user): Observable<User> {
return this.http.post<User>(this.url, user, this.httpOptions);
}
updateUser(userId, user): Observable<User> {
const putUrl = this.url + '/' + userId;
return this.http.put<User>(putUrl, user, this.httpOptions);
}
deleteUser(userId): Observable<{}> {
const deleteUrl = this.url + '/' + userId;
return this.http.delete(deleteUrl, this.httpOptions);
}
A note which is to be worth remembered.
An HttpClient method does not begin its HTTP request until you call
subscribe()
on the observable returned by that method. This is true for all HttpClient methods.
Useful Links: