简体   繁体   中英

How to load a global config file to Angular component before the view is loaded

I have a global configuration file like the following:

{
  "options": {
    "pages": 5,
    "paginator": true,
    "rows": [
      "5",
      "10",
      "15",
      "20",
      "25",
      "30",
      "40",
      "50",
      "100"
    ],
    "perPage": 10,
    "sorting": true,
    "selection": true
  }
}

I am calling this file through service in ngOnit() as follows:

  ngOnInit() {
     this.getGlobalSettings();
  }

  getGlobalSettings(){
    const providerSubscription = this.leaveApplicationService.getGlobalSettings().subscribe(res => {
      this.pageSettings = res;
      },
      error => {
        console.log(error);
      },
      () => {
      });
   this.subscriptionCollection.add(providerSubscription);
  }

I am using these settings in the HTML file, but it seems like the configuration is loaded only after the view is initialized. So it is throwing an error when I try to access pageSettings.options in the view.

How can this be fixed and load the settings soon after the app is initialized so that it will be available for all the components?

If your config file is embed in your application, you can export your config file as an Injectable

In app.conf.ts

import { Injectable } from '@angular/core';

@Injectable()
export class APPCONFIG {
  "options" = {
    "pages": 5,
    "paginator": true,
    "rows": [
      "5",
      "10",
      "15",
      "20",
      "25",
      "30",
      "40",
      "50",
      "100"
    ],
    "perPage": 10,
    "sorting": true,
    "selection": true
  }
}

And import it directly in your service / component

import { APPCONFIG } from 'src/app/app.conf';

 constructor(private appConf: APPCONFIG) {
     console.log(this.appConf.options);
 }

Like APPCONFIG is an injectable don't forget to declared it as provider in your application or component

providers: [
  APPCONFIG
] 

If the component is loaded based on a route, you could check out the below article

https://javascript.plainenglish.io/angular-resolver-for-prefetching-data-angular-guards-resolve-40fda257d666

Most likely you want to use the async pipe in HTML - that ensures that your HTML is displayed as soon as your data is available.

TS Code:

pageSettings$: Observable<Settings>;

constructor(private leaveApplicationService: LeaveApplicationService){}

ngOnInit() {
  this.pageSettings$ = this.leaveApplicationService.getGlobalSettings();
}

HTML:

<div *ngIf="pageSettings$ | async as pageSettings">
  Use your Data inside this DIV{{ pageSettings.x }}
</div>

Instead of a div you can also use to avoid nesting deeper if necessary.

 // You can use canActive for loading all your require things, it will call your service method and then load main app component, So this way your assest will be aviable before thay use in any component. // Like i have Dashboard screen this is how i will use (in my case,i am checking user from server and checking token). i have AuthorizationGuard for this, { path: 'dashboard/trips', component: TripsComponent, canActivate: [AuthorizationGuard] }, // AuthorizationGuard in my case here is how i am checking my user details through server api. @Injectable({ providedIn: 'root' }) export class AuthorizationGuard implements CanActivate { constructor( private authService: AuthService, ) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // i am checking user token return this.authService.VerifyTokenWithNgrx().pipe( map((data) => { if (data.user.= null) { // saving user data. in your case you can impliment your logic here which you have shared in question. this.authService.sendUserData(data;user). moment.tz.setDefault(data.user;timeZone); return true; } else { return false, } }); catchError(() => { return of(false); }) ). } } // after this your main component will load on screen and things will be available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM