在我的Angular 8应用程序中,我想在应用程序加载之前通过API调用获取组织列表。我正在使用APP_INITIALIZER这样做。但是,当应用程序加载完成时,将不再按预期设置服务上所选组织的属性。
app.module.ts
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { OrganizationsService } from './services/organizations.service';
export function orgResolverFactory(provider: OrganizationsService) {
return () => provider.setOrgs();
}
providers: [ SidenavService, OrganizationsService, { provide:
APP_INITIALIZER, useFactory: orgResolverFactory, deps:
[OrganizationsService], multi: true }
]
organizations.service.ts
@Injectable()
export class OrganizationsService {
constructor(private http: HttpClient) {}
orgs: any = [];
selectedOrg: any;
setOrgs() {
return new Promise((resolve, reject) => {
this.http.get<Org>(`/api/orgs`,{ observe: 'response' })
.subscribe(resp => {
this.selectedOrg = resp.body[0]
// breakpoint here shows this.selectedOrg is set
resolve(true);
});
})
}
public getSelectedOrg() {
return this.selectedOrg;
}
}
metrics.service.ts
import { Org, OrganizationsService } from './organizations.service';
@Injectable()
export class MetricService {
selectedOrg: any;
constructor(private http: HttpClient, private organizationsService:
OrganizationsService) {
this.selectedOrg = this.organizationsService.getSelectedOrg();
// breakpoint shows this.selectedOrg is undefined
}
}
我迷茫的是为什么加载应用程序后未定义OrganizationsService中的selectedOrg。我希望能够在指标服务中引用selectedOrg以进行进一步的API调用。如何在应用加载之前设置此参数,然后在以后引用它?这甚至是正确的方法吗?
答案 0 :(得分:0)
最后,我决定从使用服务切换为通用提供程序。这使我可以根据需要设置和检索属性。在我上面的代码中,服务通常在运行时实例化。即使我在初始化之前就使用了我的服务,但在加载应用程序时它会被重置。希望在此处发布此答案,以防其他人正在尝试做类似的事情并且遇到类似的问题。
org-provider.ts
import {Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class OrgsProvider {
private selectedOrg: any = null;
private orgs: any = null;
constructor(private http: HttpClient) {
}
public getSelectedOrg() {
return this.selectedOrg;
}
public getOrgs() {
return this.orgs;
}
loadOrgs() {
return new Promise((resolve, reject) => {
this.http.get(`/api/orgs`,{ observe: 'response' })
.subscribe(resp => {
this.orgs = resp.body
this.selectedOrg = resp.body[0]
resolve(true);
});
})
}
setSelectedOrg(id:number){
this.selectedOrg = this.orgs.find((org)=>{
return org.id == id
})
return this.selectedOrg
}
}