Have four services
- Global
- UserService
- 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;
}
}
}
UserService
@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 : Customized http service to handle generically across 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 the httpUtil so through out application you should use HttpUtil and not Http
from @angular/http
Let me know if you need any more explanations
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…