【问题标题】:Angular2 : How to load JSON data before App initAngular2:如何在应用程序初始化之前加载 JSON 数据
【发布时间】:2017-07-30 10:18:32
【问题描述】:

在我的 Angular 应用程序中,我想在应用程序初始化之前加载 JSON 数据,我将其存储在服务中并在整个应用程序中使用它。

按照Angular2 load configuration from backend on startup 的建议,我使用解析器在应用程序初始化之前加载数据。但是当我执行 ng serve 或 ng build 时,该解决方案引发了错误。

错误中的错误遇到静态解析符号值。不支持函数调用。考虑将函数或 lambda 替换为对导出函数的引用(原始 .ts 文件中的位置 43:19),解析 /Users/name/src/app/app.module.ts 中的符号 AppModule

请让我知道如何解决此错误,或者是否有任何其他方式可以在应用程序初始化之前加载数据。

app.module.ts

import { APP_INITIALIZER } from '@angular/core';
import { SearchService } from './backend.service';
import { BackendResolver } from './backend.resolver';
import { MyService } from './my.service';

providers: [
SearchService,
{ provide: APP_INITIALIZER,
  useFactory: (config:SearchService) => () => config.call(),
  deps: [SearchService],
  multi: true },
  BackendResolver,
  MyService
 ],
 bootstrap: [AppComponent]

backend.service.ts

import { Inject, Injectable } from '@angular/core';
import { Http, URLSearchParams, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class SearchService {
jsonData;
constructor(
    private http: Http,
) { }

call() {
    return new Promise((resolve) => {
        this.http.get('assets/appData.json').map(res => res.json())
            .subscribe(jsonData => {
                this.jsonData = jsonData;
                resolve();
            });
    });
  }
}

backend.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { SearchService } from './backend.service';

@Injectable()
export class BackendResolver implements Resolve<any> {
  constructor(
  private searchService: SearchService
  ) {}

resolve(route: ActivatedRouteSnapshot): Promise<any> {
  return this.searchService.call();
 }
}

my.service.ts

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

@Injectable()
export class MyService {
    resources;
    constructor() { }
    public getData() {
        return this.resources;
    }

    public saveData(param) {
        this.resources = param;
    }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
import { SearchService } from './backend.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  jsonData: any;
  constructor(
    private myService: MyService,
    private searchService: SearchService
    ) {}
    ngOnInit() {
      this.jsonData = this.searchService.jsonData;
      this.myService.saveData(this.jsonData);
    }
}

footer.component.ts

    import { Component, OnInit } from '@angular/core';
    import { MyService } from '../my.service';
    @Component({
        selector: 'my-footer',
        templateUrl: './footer.component.html',
        styleUrls: ['./footer.component.scss']
    })
    export class FooterComponent implements OnInit {
        contactUs: any;
        constructor(
            private myService: MyService
        ) { }
        ngOnInit() {
            this.contactUs=this.myService.getData().contactUs;
        }
    }

【问题讨论】:

  • 为什么不能这样.searchService.call().then((jsonData)=>{ this.jsonData=jsonData })
  • 这种方法存在一个问题。在 app.component.ts 中添加了上述回调,这将等待调用后的结果,然后结果可以存储在 myService 中。但是,在页脚中我们调用了 myService.getData(),它在 setData 方法()之前被调用,导致错误“无法读取未定义的属性 'contactUs'”
  • 如果您谈论的是 HTML 模板中的未定义错误,我建议将 *ngIf="contactInfo" 添加到您要访问您的contactInfo的任何div中

标签: angular angular2-services


【解决方案1】:

这是一个烦人的问题......它就在这里:

{ provide: APP_INITIALIZER,
  useFactory: (config:SearchService) => () => config.call(),
  deps: [SearchService],
  multi: true 
}

您不能对自定义提供程序工厂函数使用箭头语法。将其更改为显式函数,例如:

useFactory: function(config:SearchService) {
    return config.call();
}

【讨论】:

  • 删除了箭头语法并按照建议编写函数,但仍然抛出相同的错误。
猜你喜欢
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2017-05-31
  • 1970-01-01
  • 2016-05-17
相关资源
最近更新 更多