Inserting Users
This lesson explains how to insert a user into the database. It focuses on the UserService class and the backend implementation of the insertion operation.
We'll cover the following...
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:
Press + to interact
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
...