C
C
Coder3212016-09-23 16:14:46
JavaScript
Coder321, 2016-09-23 16:14:46

How to download data from the server before the application loads?

I'll send a little bit of work on Angular 2 for the purpose of learning. The question arose, how can I download something from the server before the application loads? That is, I have a token, I need to send it to the server, check the user and send back the data of this user. There are no problems with the server part, but I can’t think of how to do it on the client. Or chain guard to the main module or resolve. How will it be right?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Zuev, 2016-09-24
@Coder321

You can use the APP_INITIALIZER
token specially created for this. Thanks to it, the application will not start until the data is received.
This is done approximately as follows.
Register a global service and this token in providers

providers: [
  GlobalService,
  {
    provide: APP_INITIALIZER,
    useFactory: (service: GlobalService) => () => service.init(),
    deps: [GlobalService], multi: true
  }
],

Service is like this
@Injectable()
export class GlobalService {
    data: any;
    constructor(private http: Http) { }
    init(): Promise<any> {
        var promise = this.http.get('src/data.json').map(res => res.json()).toPromise();
        promise.then(data => this.data = data);
        return promise;
    }
}

And then you get, for example, your data in the root component
export class AppComponent {
  constructor(private service: GlobalService) {
    console.log(service.data);
  }
}

Live example

A
Alexander Korotaev, 2016-09-23
@lekzd

Add resolver to root state

A
antkhnvsk, 2016-09-23
@alch

in main.ts:

fetch('//your-url.com/api?token=' + token, { method: 'get' })
  .then(apiData => {
    platformBrowserDynamic([
      provide('apiData', { useValue: apiData })
    ]).bootstrapModule(AppModule)
  })

in app.component.ts or any other component:
export class AppComponent{
  constructor( @Inject('apiData') apiData) {
    console.log(apiData)
    // use your apiData here...
  }
}

I
ITZver, 2017-06-22
@ITZver

Via APP_INITIALIZER. I wrote more in my blog
Executing code before starting the application via APP_INI...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question