我正在使用一个服务,该服务实现了一个名为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 {}
应用服务.ts
import { Injectable, ... } from '@angular/core';
...
@Injectable({
providedIn: 'root'
})
export class AppService {
loadConfig(): Promise<any> { ... }
}
文件.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);
}
}
在组件中,我changeListType
从调用该方法时file.service
,它会检索数据,但该_publishData
方法显示this.appService
用于构建 的node.fullPath
未定义。如果我将_getAllFiles
方法订阅者中的调用更改为:
this.httpClient.get<any>(`${this.appService.config.api}/api/files/`)
.subscribe((data: any) => { this._publishData(data); });
该appService
变量不再不确定的。这是故意的还是一种与范围变量相关的错误/错误?或者也许我在我的代码逻辑中遗漏了一些东西。
提前致谢。
您的范围有问题this
:
在您的第二种方法中,您没有变得appService
未定义,因为您是_publishData
从箭头函数中引用函数。箭头函数不会创建自己的函数,而是this
使用其外部作用域中的 this。当_publishData
函数在这种情况下被调用this
它所引用的是this
组件,而不是功能的this
在此处阅读有关箭头函数的更多信息。
如果您不使用箭头函数并希望获得this
订阅者函数的正确值,则需要绑定this
您需要绑定正确的 this 才能_publishData
发挥作用
private _getAllFiles() {
this.httpClient.get<any>(`${this.appService.config.api}/api/files/`)
.subscribe(this._publishData.bind(this));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句