Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an rest api while bootstrapping angular 2 app

Tags:

angular

We would like to call a rest api when angular 2 app being bootstrapped, i mean first thing it should do about the application is call this api and get some data which is required for application.

Is there anyway to achieve this? I saw following article but it was meant for beta version of Angular 2

Sample Code based on Angular 2 beta or rc

Reading data before app start up

like image 946
user509755 Avatar asked Jan 12 '17 17:01

user509755


People also ask

How Apis can be called in Angular?

We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10.

Which file is responsible for bootstrapping an Angular app?

Every application has at least one Angular module, the root module, which must be present for bootstrapping the application on launch. By convention and by default, this NgModule is named AppModule . After the import statements is a class with the @NgModule decorator.


1 Answers

You can use APP_INITIALIZER to call a service method at bootstrap. You will require to define a provider for it in your AppModule.

Here is an example of how to do this.

StartupService (startup.service.ts)

import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http';  import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise';  @Injectable() export class StartupService {      private _startupData: any;      constructor(private http: Http) { }      // This is the method you want to call at bootstrap     // Important: It should return a Promise     load(): Promise<any> {          this._startupData = null;          return this.http             .get('REST_API_URL')             .map((res: Response) => res.json())             .toPromise()             .then((data: any) => this._startupData = data)             .catch((err: any) => Promise.resolve());     }      get startupData(): any {         return this._startupData;     } } 

AppModule (app.module.ts)

import { BrowserModule } from '@angular/platform-browser'; import { NgModule, APP_INITIALIZER } from '@angular/core';  import { StartupService } from './startup.service';  // ... // Other imports that you may require // ...   export function startupServiceFactory(startupService: StartupService): Function {     return () => startupService.load(); }  @NgModule({     declarations: [         AppComponent,         // ...         // Other components & directives     ],     imports: [         BrowserModule,         // ..         // Other modules     ],     providers: [         StartupService,         {             // Provider for APP_INITIALIZER             provide: APP_INITIALIZER,             useFactory: startupServiceFactory,             deps: [StartupService],             multi: true         }     ],     bootstrap: [AppComponent] }) export class AppModule { } 

EDIT (How to handle startup service failure):

AppComponent (app.component.ts)

import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router';  import { StartupService } from './startup.service';  @Component({     selector: 'app-root',     templateUrl: './app.component.html',     styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit {      constructor(private router: Router, private startup: StartupService ) { }      ngOnInit() {          // If there is no startup data received (maybe an error!)         // navigate to error route         if (!this.startup.startupData) {             this.router.navigate(['error'], { replaceUrl: true });         }     }  } 
like image 155
Santanu Biswas Avatar answered Sep 23 '22 05:09

Santanu Biswas