Set the global data to the property from the receive request before proceeding

I have an angular app with one common service to help me share data across all components.

General service

@Injectable() export class ShareService { userData: []; selectedMonth: number; selectedYear: number; } 

User service

 @Injectable() export class UserService { baseApiUrl = environment.api_base_url; constructor(private http: Http, private cookie: CookieService) { } getUserData() { return this.http.get(this.baseApiUrl + 'api/get-user-data' + this.cookie.get()) .map((res: Response) => res.json()); } 

AppComponent

 export class AppComponent implements OnInit { isAuth: boolean = false; isAdmin: boolean; constructor(private auth: AuthService, private user: UserService, private share: ShareService) { } ngOnInit() { this.setUser(); } setUser() { this.user.getUserData().subscribe( (data) => { this.share.user = data; console.log(data); } ); } } 

The userData property is set after the completion of the observed request. Since the application uses userData, I would like to populate this property before performing other actions.

What is the best way to do this? Is there a way to make a synchronous http call?

0
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1268417/


All Articles