You have four services
- Global
- User service
- HTTPUTIL
- Authentication
Global service
@Injectable() export class Global { constructor(private userService: UserService, private router: Router) { if (!this.isAuthenticatedUser()) { this.router.navigateByUrl('/login'); } } handleError(error: Response) { console.log(error); return Observable.throw(error.json().error || 'Internal Server error'); } isAuthenticatedUser(): boolean { let user = this.userService.getUser(); if (_.isEmpty(user)) { return true; } else { return false; } } }
User service
@Injectable() export class UserService { constructor() { } setUser(user: User) { // store user details and jwt token in local storage to keep user logged in between page refreshes localStorage.setItem('currentUser', JSON.stringify(user)); } getUser(): User { // get the current user from local storage to keep user logged in between page refreshes return <User>JSON.parse(localStorage.getItem('currentUser')); } clearUser() { localStorage.removeItem('currentUser'); } }
HttpUtil: a custom HTTP service for processing through the entire application
export class HttpUtil { private headers: Headers; constructor( private globalConstants: GlobalConstants, private http: Http,private userService: UserService, private global: Global) { this.headers = new Headers( { 'Content-Type': 'application/json' }, ); } get(url: string, options?: RequestOptionsArgs): Observable<Response> { if (this.global.isAuthenticatedUser()) { let token = this.userService.getUser().token; this.headers.append('Authorization', 'JWT ' + token); if (!options) { this.headers.forEach((header: any) => { options.headers.append(header.name, header.value); }); options.withCredentials = true; } return this.http.get(url, options); } } post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> { if (this.global.isAuthenticatedUser()) { let token = this.userService.getUser().token; this.headers.append('Authorization', 'JWT ' + token); if (!options) { this.headers.forEach((header: any) => { options.headers.append(header.name, header.value); }); options.withCredentials = true; }
AuthenticationService - calls httpUtil, so through the application you should use HttpUtil , not Http from @angular/http
Let me know if you need more explanation.
source share