Home > Blockchain >  Call function in service as soon as possible in Angular?
Call function in service as soon as possible in Angular?

Time:11-03

My page should load content from a backend (Contentful.com) as soon as possible. Im loading the backend content in an extra service, which is registered in my root module. How do I make sure, that the function getContent() in this service is called as soon as possible?:

import { Injectable } from '@angular/core';
import {environment} from 'src/environments/environment.local';

@Injectable({
  providedIn: 'root'
})
export class GetContentService {

  constructor() { }

  getContent() {
   loadingMyContentIntoAnObservable.then(content => 
      console.log("received the content", content");
  }
}

My idea was to create a Home component that has the service in the constructor and then in ngOnInit() of this component call getContentService.getContent(). But is this the fastest way? (I know it's only a matter of milliseconds, but I want to learn the right / best way...)

CodePudding user response:

If you want to call your backend before the app starts as part of bootstrapping you could use an APP_INITIALIZER.

Usage:

function initializeApp(): Promise<any> {
  return new Promise((resolve, reject) => {
    // Do some asynchronous stuff
    resolve();
  });
}

@NgModule({
 imports: [BrowserModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent],
 providers: [{
   provide: APP_INITIALIZER,
   useFactory: () => initializeApp,
   multi: true
  }]
 })
export class AppModule {}

But you have to be aware that this can delay application startup time and most of the time is not what you want as you can't provide meaningful visual feedback to the user calling your appp.

CodePudding user response:

That would work, though it might be easier to just send the request in the constructor of the service:

export class GetContentService {
  constructor() {
    loadingMyContentIntoAnObservable.then(content => 
      console.log("received the content", content");
  }
}

However, sending the request as early as possible does not mean the response will arrive instantly (or at all; requests can fail), so you still need to deal with the data being unavailable while the request is in transit.

PS: Yes, you could wait to initialize angular until the response arrives, but this delays the time until first meaningful render of your app, and will cause users to perceive your app as slow. It's probably better to render as much as you can instantly, and only hide those features that really need the data being fetched.

  • Related