Call app.service when reloading page

1

When you start the application, the getBanners() function of the banners.service.ts service is executed first, and then the this.headers of the app.service.ts service is changed.

If I switch pages, it works normally. The error only occurs when starting the application.

I want the banners.service.ts to execute the function only after this.headers of the service app.service.ts has been changed.

banners.service.ts

getBanners(){
    return this._http.get(this.appService.endpoint + 'banners', { headers: this.appService.headers })
  .toPromise()
  .then((data) => {
    data = data.json();
    return data;
  });
}

app.service.ts

constructor() {
    this.getContentType().then(data => {
        this.headers.set('Content-Type', data);
    });
}

private getContentType(): Promise<any> {
    return 'application/json';
}
    
asked by anonymous 21.05.2018 / 16:17

2 answers

1

In Angula 2+ you do not work linearly, hoping to load this or that first ... Have a shared service between all the components. Within the service, declare a variable that contains the value that you want to share between the components. Then use getter and setter to assign, retrieve, or modify the service variable.

  

shared.service.ts :

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService{
    headers;

    constructor(){
      this.headers = '';
    }

    setHead(token: string){
      this.headers = new Headers({
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            });;
    }

    getHead(){
      return new RequestOptions({ headers: this.headers });
    }
}
  

Add the service to app.module.ts Providers:

@NgModule({
  ...
  providers: [ SharedService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
  

In component.ts inject the service and use it to define, retrieve or modify the variable.

constructor(private appService: AppService) { }

  changeHead(){
    let currentUser = JSON.parse(localStorage.getItem('User'));
    this.appService.setHead(currentUser.token);
  }


getBanners(){
    return this._http.get(this.appService.endpoint + 'banners', { headers: this.appService.getHead() })
  .toPromise()
  .then((data) => {
    data = data.json();
    return data;
  });
}
    
22.05.2018 / 14:27
0

You can do by inheritance in this case the header will always be right.

@Injectable()
export class BannersService extends AppService{
   constructor() {
      super()
   }

   getBanners(){
        return this.httpClient.get(this.endpoint + 'banners', { headers: this.headers })     
    }
}

App.service.ts

constructor(private httpClient: HttpClient) {    
      this.headers.set('Content-Type', 'application/json');      
}
    
22.05.2018 / 13:52