Created
October 10, 2017 12:51
-
-
Save xtrasmal/19624d3e70d865742cd132f772843653 to your computer and use it in GitHub Desktop.
Angular user service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Http, Headers, RequestOptions, Response } from '@angular/http'; | |
import { User } from '../_models/index'; | |
@Injectable() | |
export class UserService { | |
constructor(private http: Http) { } | |
getAll() { | |
return this.http.get('/api/users', this.jwt()).map((response: Response) => response.json()); | |
} | |
getById(id: number) { | |
return this.http.get('/api/users/' + id, this.jwt()).map((response: Response) => response.json()); | |
} | |
create(user: User) { | |
return this.http.post('/api/users', user, this.jwt()).map((response: Response) => response.json()); | |
} | |
update(user: User) { | |
return this.http.put('/api/users/' + user.id, user, this.jwt()).map((response: Response) => response.json()); | |
} | |
delete(id: number) { | |
return this.http.delete('/api/users/' + id, this.jwt()).map((response: Response) => response.json()); | |
} | |
// private helper methods | |
private jwt() { | |
// create authorization header with jwt token | |
let currentUser = JSON.parse(localStorage.getItem('currentUser')); | |
if (currentUser && currentUser.token) { | |
let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token }); | |
return new RequestOptions({ headers: headers }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment