Angular2 load data from backend before view loads

2.5k views Asked by At

I have written the service code like this to read from backend

getData(): any { 

    let headers = new Headers(
      {

      });
    let options = new RequestOptions({ headers: headers });

    return this.httpClient.get('https://link', options)
      .map((res: Response) => res.json())
      // .do(data => console.log('All data: ' + JSON.stringify(data)))
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));

and the code to load data

ngOnInit() {
    this.service.getData().subscribe(
      (res) => {this.Data = res},
      (error) => this.errorMessage = <any>error);
}

but here it's getting data after the view loads so it's giving error.

How to load the data before view loads??

2

There are 2 answers

2
Karl On

Best option is to use a Routeresolver. Resolvers are part of the route definition and intended to provide data before a route is activated. So if the view is shown you can get the provided data in the ngOnInit. You just have to use your code to fetch data in the resolver

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { DataService } from './DataService';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class MyDataResolve implements Resolve<any> {

    constructor(private dataService: DataService) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any     {

        let id = +route.params['id'];
        return this.dataService.getRecords('MT_Entity', id);    
    }
}

In the Component: export class BesuchdetailComponent {

   ngOnInit(): void {
     // Initialize form values, Prepare for SELECTS, ...
     let rawdata: any;
     this.rawbobject = this.route.snapshot.data['myobject'];
   }
 }

Add Routerdefinition:

export const AppRoutes: Routes = [
{

    {
       path: 'objectdetail/:id',
       component: YourComponent,
       resolve: {
          myobject: BesuchResolve
       }
    },
  }
1
harold_mean2 On

Angular 2 is an OOP like Java and C++ using classes. I advice you to start using classes at your service file. The link below is a solution that you may be looking for. Hope this helps. Happy coding..

   Angular 2 , MEAN Stack : Receiving JSON instead of HTML