El Hombre Sin Nombre
El Hombre Sin Nombre

Reputation: 3092

Angular2 - Preload multiple service before view load

I been working in Angular (v8) and I'm searching the most simple method to load data before a view is loaded.

I need to load two services and save in the localStore. I load services in header of page on ngOnInit function, like this

 ngOnInit() {
    this.usuario = localStorage.getItem("user");
    this.entityCtrl.getEntityByUser(localStorage.getItem("user")).subscribe(
      response => {
        this.entidadesTodos = response["body"];
        this.entidad = this.entidadesTodos[0]["id"];
        localStorage.setItem("entidad", this.entidad.toString());
      },

      (error: any) => {
        console.log(error);
      }
    );

    this.entityCtrl
      .getGroupsByEntityAndUser(
        localStorage.getItem("entidad"),
        localStorage.getItem("user")
      )
      .subscribe(
        response => {
          this.groupsTodos = response["body"];
          this.grupo = this.groupsTodos[0]["id"];
          localStorage.setItem("grupo", this.grupo.toString());
        },
        (error: any) => {
          console.log(error);
        }
      );
  }

The problem is: The services loads after view so 'brokes' the page (web need the value of this services to work).

The question is: What is the most simple method to load services before the view is loaded?

---UPDATE: TRY RESOLVE---

Service

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { Resolve } from "@angular/router";

const httpOptions = {
  headers: new HttpHeaders({
    Authorization: "Token " + localStorage.getItem("token")
  })
};

const httpOptions2 = {
  headers: new HttpHeaders({
    "Content-Type": "application/json",
    Authorization: "Token " + localStorage.getItem("token")
  })
};

@Injectable({
  providedIn: "root"
})
export class EntityService implements Resolve<any> {
  constructor(private http: HttpClient) {}
  resolve(): Observable<any> {
    return this.http.get(
      "URL" +
        localStorage.getItem("user"),
      httpOptions
    );
  }
}

Routes

import { EntityService } from "../services/entitites/entity.service";

@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: "",
        component: AdminComponent,
        children: [
          {
            path: "principal",
            component: HomeComponent,
            canActivateChild: [AuthGuard],
            resolve: {
              entidad: EntityService
            }
          },

Header

 this.activatedRoute.data.subscribe(response => {
      this.entidadesTodos = response.entidad["body"];
      console.log(this.entidadesTodos);
      this.entidad = this.entidadesTodos[0]["id"];
      localStorage.setItem("entidad", this.entidad.toString());
    });

Return null.

Upvotes: 0

Views: 255

Answers (2)

Dmitry Vasilkov
Dmitry Vasilkov

Reputation: 76

simple the way use *ngIf in your template:

<div *ngIf = 'some'></div>

then

this.entityCtrl.getEntityByUser(localStorage.getItem("user")).subscribe(
      response => {this.some = true});

so you the view will not be shown before you get data in your services.

Upvotes: 0

Udi Mazor
Udi Mazor

Reputation: 1826

Use resolvers as it will prefetch your data before you are navigated to the page. There is a stackblitz example here

You can also read about it at the resolve page in angular.io

Upvotes: 1

Related Questions