Search⌘ K

Inserting Users

Explore how to implement user data insertion in a MEAN stack application by connecting Angular front end with a Node.js and Express back end, using Mongoose to save user data in MongoDB. Learn the full process from HTTP POST requests to back-end API handling and database storage.

In the previous lesson, we looked at the typescript and HTML files. Now, let’s take a look at the implementation of UserService and the back-end implementation for the insertion of a user.

UserService

This class is in charge of communication with the back-end through the Web API and, because of that, it has to use Angular’s HTTP service.

Example

Here is the code in the /mean_frontend/src/app/services/users.service.ts file:

C++
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { User } from '../model/user';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class UserService {
constructor(private http: Http) {
}
insertNewUser(user:User): Observable<any>{
return this.http.post("http://localhost:3000/insertUser", user)
.map((res:any) => {
return res.json();
})
.catch((error:any) => {
return Observable.throw(error.json ? error.json().error : error || 'Server error')
});
}
}

So, this class sends an HTTP POST ...