簡體   English   中英

Angular 7-可觀察到的服務訪問未定義

[英]Angular 7 - Accessing to service returns undefined in observable

我正在使用一種服務,該服務實現名為AppService的全局服務,該服務存儲一些全局應用程序配置。

首先,我將在這里發布一些代碼:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector, APP_INITIALIZER } from '@angular/core';
import { AppService } from './app.service';

...

export function appLoadConfig(appService: AppService) {
  return () => appService.loadConfig();
}

@NgModule({
  imports: [
    BrowserModule,
    CoreModule,
    ...
  ],
  declarations: [
    AppComponent,
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appLoadConfig,
      deps: [ AppService ],
      multi: true
    }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.service.ts

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

...

@Injectable({
  providedIn: 'root'
})
export class AppService {

  loadConfig(): Promise<any> { ... }

}

file.service.ts

import { Injectable } from '@angular/core';
import { AppService } from '../../app.service';
...

@Injectable()
export class FileService {

  filesChange: BehaviorSubject<FileNode[]> = new BehaviorSubject<FileNode[]>([]);

  constructor(
    private appService: AppService,
    private httpClient: HttpClient) { }

  changeListType(types: string[]) {
    this._getAllFiles();
  }

  private _getAllFiles() {
    this.httpClient.get<any>(`${this.appService.config.api}/api/files/`)
        .subscribe(this._publishData);
  }

  private _publishData(data: FileNode[]) {
    let nodeData: FileNode[] = [];
    data.forEach((n: any) => {
      const node = new FileNode(n);
      node.fullPath = `${this.appService.config.api}/uploads/${node.uri}`;
      nodeData.push(node);
    });
    this.filesChange.next(nodeData);
  }
}

當在分量I調用changeListType方法從file.service ,它檢索數據,但_publishData方法表明this.appService ,用於構建node.fullPath ,是不確定的。 如果我將_getAllFiles方法訂戶中的調用更改_getAllFiles調用:

this.httpClient.get<any>(`${this.appService.config.api}/api/files/`)
            .subscribe((data: any) => { this._publishData(data); });

appService變量不再是未定義的。 這是故意的還是一種與范圍變量有關的錯誤/錯誤? 也許我的代碼邏輯中缺少某些內容。

提前致謝。

this范圍有this

在第二種方法中,您不會因為未通過箭頭函數引用_publishData函數而將appService設為未定義狀態。 箭功能,不自己創建this並使用這個從它的外部范圍。 _publishData功能在這種情況下被調用的this其所引用的是this部件的,而不是功能的this

在此處閱讀有關箭頭功能的更多信息。

如果您使用的不是箭功能,並希望得到正確的this對於用戶的功能,您將需要綁定this

您需要將正確的綁定到_publishData函數

  private _getAllFiles() {
    this.httpClient.get<any>(`${this.appService.config.api}/api/files/`)
        .subscribe(this._publishData.bind(this));
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM