无法访问组件中现有服务的属性

时间:2018-12-05 09:21:10

标签: angular service constructor components

我创建了一个服务简单服务,该服务首先从JSON文件加载配置。因为我希望启动应用程序时数据可用,所以我正在使用APP_INITIALIZER加载数据。

在服务本身中,数据可用,一切都很好。但是,当我从组件内部使用服务时,它会产生奇怪的行为。请有人可以解释我的代码有什么问题吗?

filterService.ts

export class FilterService {
   url:string = '/admin2/src/assets/import.filter.json';
   filters: Filter[];
   currentFilter: Filter;

   public loadFilters() {

      this.http.get(this.url).subscribe(response => {
        this.filters = <Filter[]>response;

        if (this.filters[0])
            this.currentFilter  = this.filters[0];
    });
}

此服务在应用初始化期间加载

app.module.ts

 @NgModule({
 ...
 providers: [
    FilterService,
    { provide: APP_INITIALIZER, useFactory: (filterService: FilterService) => () => filterService.loadFilters(), deps: [FilterService], multi: true },
 ],
 ...

最后,我正在执行的操作是

filter.component.ts

constructor(private filterService: FilterService) {}

ngOnInit() { 
    console.log('import initialized'); 

    console.log(this.filterService);
    console.log(this.filterService.currentFilter);
    console.log(this.filterService.filters);
    console.log(this.filterService.getFilters());
}

现在我真的不明白console.log中发生了什么

  Object { http: {…}, url: "http://...}   // as expected
  undefined                               // ??                               
  undefined                               // ??
  undefined                               // ??

为什么我不能访问对象属性?在我看来,一切都很好并且可用。...

1 个答案:

答案 0 :(得分:0)

在您的情况下=>

app-load.module.ts

filter_horizontal

app.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from "@angular/common/http";

import { FilterService } from './filter.service';

export function load_filters(filterService: FilterService) {
    return () => filterService.loadFilters();
}

export function get_filters(filterService: FilterService) {
    return () => filterService.getFilters();
}

@NgModule({
  imports: [HttpClientModule],
  providers: [
    AppLoadService,
    { provide: APP_INITIALIZER, useFactory: load_filters, deps: [FilterService], multi: true },
    { provide: APP_INITIALIZER, useFactory: get_filters, deps: [FilterService], multi: true }
  ]
})
export class AppLoadModule { }

我已关注此博客来创建我的APP_INITIALIZER =>请阅读一次(可能有用) https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/