注入的服务未在函数中定义,但在ngInit中未定义

时间:2019-06-28 09:43:05

标签: angular dependency-injection angular7

我正在尝试将HttpService注入我的CoreModule中。这在ngOnInit函数中有效,但是当我尝试在其他函数中访问服务时,该服务变得不确定。

Component

export class TreeComponent implements OnInit {
  constructor(private store: Store<AppState>,
    private cdRef: ChangeDetectorRef,
    private injector: Injector,
    private locationService: LocationService) { }

async ngOnInit() {
  await this.store.pipe(
  select('auth'),
  map(async (authState) => {
    if (authState.isAuthenticated) {
      console.log(this.locationService);
      this.data.push(await this.injector.get(LocationService).getBaseLocation().toPromise());
      this.cdRef.detectChanges();
      console.log(this.locationService);
    }
  })
  ).toPromise();
}
/* Ommited where not used */

public hasChildren(node: any): boolean {
  console.log(node);
  console.log(this.locationService); <-- undefined
  console.log(this.injector); <-- undefined
  //Check if the parent node has children.
  return true;
}

CoreModule

@NgModule({
  declarations: [ShellComponent, SidebarComponent, TreeComponent],
  imports: [
    CommonModule,
    RouterModule,
    SharedModule,
    TreeViewModule,
    FormsModule
  ],
  exports: [

  ],
  providers: [AuthService, Shell, LocalizationService, LocationService]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error(`${parentModule} has already been loaded. Import Core module in the AppModule only.`);
    }
  }
}

App Module

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createCustomTranslateLoader),
        deps: [HttpClient]
      },
      missingTranslationHandler: {
        provide: MissingTranslationHandler,
        useClass: CreateMissingTranslationHandler,
        deps: [HttpClient]
      },
      useDefaultLang: true
    }),
    StoreModule.forRoot(reducers, { metaReducers }),
    !environment.production ? StoreDevtoolsModule.instrument({
      maxAge: 25 //  Retains last 25 states
    }) : [],
    EffectsModule.forRoot([AuthEffects]),
    CoreModule,
    SharedModule,
    ProductionOverviewModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: (initI18n),
      deps: [
        HttpClient,
        TranslateService,
      ],
      multi: true
    },
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

LocationService

const headers = new HttpHeaders({
 'Content-Type': 'application/json'
});

@Injectable()
export class LocationService {
public currentPlant: BehaviorSubject<Location>;

constructor(private http: HttpClient) {
 this.currentPlant = new BehaviorSubject<Location>(null);
}

getBaseLocation(): Observable<Location> {
 return this.http.get<Location>(environment.API_BASE_URI + '/Location/GetBaseLocation', { headers: headers })
  .pipe(map(location => {
    this.currentPlant.next(location);
    location.childeren = [];
    return location;
  }));
}

getChildLocations(locationId: string): Observable<Location[]> {
   return this.http.get<Location[]>(environment.API_BASE_URI + `/Location/GetLocationTree?upperLocationID=${locationId}`, { headers: headers })
  .pipe(map(location => {
    return location;
  }));;
}
}

我尝试了多种操作,例如在应用程序模块中导入服务,尝试将服务分配给变量,..但它仍未定义。希望有人可以指出正确的方向。

2 个答案:

答案 0 :(得分:1)

这是因为从kendo-treeview组件调用了“ hasChildren”函数,要求您在传递当前上下文之前将其绑定到该函数。

更改

[hasChildren]="hasChildren"

收件人

[hasChildren]="hasChildren.bind(this)"

会成功的

答案 1 :(得分:1)

假设hasChildren函数是从HTML中的kendo-treeview组件中调用的,则应使用Function.prototype.bind函数:

<kendo-treeview
  kendoTreeViewExpandable
  [nodes]="data"
  textField="text"
  [children]="fetchChildren"
  [hasChildren]="hasChildren.bind(this)">
                 ^^^^^^^^^^^^^^^^^^^^^^
</kendo-treeview>

这里发生的事情是当执行hasChildren时,范围不同,因此this不是您所期望的。

bind函数返回绑定到您定义的this的新函数。