UNPKG

groceries-angular-service

Version:

Angular Service to be used with the sample groceries project

54 lines (47 loc) 1.38 kB
import { Injectable, Inject, forwardRef } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; import { User } from './models/user'; import { Config } from './models/config'; @Injectable() export class UserService { constructor(@Inject(forwardRef(() => Http)) private http: Http) {} register(user: User) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.post( Config.apiUrl + 'Users', JSON.stringify({ Username: user.email, Email: user.email, Password: user.password }), { headers: headers } ) .catch(this.handleErrors); } login(user: User) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.post( Config.apiUrl + 'oauth/token', JSON.stringify({ username: user.email, password: user.password, grant_type: 'password' }), { headers: headers } ) .map(response => response.json()) .do(data => { Config.token = data.Result.access_token; }) .catch(this.handleErrors); } handleErrors(error: Response) { console.log(JSON.stringify(error.json())); return Observable.throw(error); } }