Answer the question
In order to leave comments, you need to log in
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
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
}
],
@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;
}
}
export class AppComponent {
constructor(private service: GlobalService) {
console.log(service.data);
}
}
in main.ts:
fetch('//your-url.com/api?token=' + token, { method: 'get' })
.then(apiData => {
platformBrowserDynamic([
provide('apiData', { useValue: apiData })
]).bootstrapModule(AppModule)
})
export class AppComponent{
constructor( @Inject('apiData') apiData) {
console.log(apiData)
// use your apiData here...
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question