我正在从另一个文件(组件)中加载数据,并且当我从一个函数中对其进行控制台时,在发生事件后它可以工作:
updateSub(data) {
console.log('attempting to print the subsid array' +
this.engagementService.orgSubSidNames)
}
当我尝试在此范围之外和范围之外但在我的ngOnit范围内呼出时 它的控制台为空:
console.log('attempting to print the subsid array initially' +
this.engagementService.orgSubSidNames)
所有代码都包含在我的ngOnit中。 我还在构造函数中包含了engagementService,这就是我访问它的方式:
export class EngagementFilterComponent implements OnInit {
constructor(private builder: FormBuilder, public engagementService:
EngagementService) { }
ngOnInit(): void {
console.log('attempting to print the subsid array initially' +
this.engagementService.orgSubSidNames)
}
}
在参与服务中,我像这样拨打http:
organizationSubsidiaries(sfid: string) {
const url = `${this.baseURL}/${ENDPOINTS.organizations}/${this.organization.id}/${ENDPOINTS.subsidiaries}`;
return this.http.get(url).map(res => res.json());
}
然后在加载浏览器时就这样调用,然后我从响应中创建所需的数组:
this.organizationSubsidiaries(id)
.subscribe(data => {
let subsidiaryNames = []
data.forEach(sub => {
console.log(sub.SubsidiaryName)
subsidiaryNames.push(sub.SubsidiaryName)
})
subsidiaryNames = subsidiaryNames.filter(this.onlyUnique);
this.orgSubSidNames = subsidiaryNames;
console.log('data from subsidiaries' + JSON.stringify(this.orgSubSidNames))
});
因此,另一个使用可观察对象(我可能会丢失)的呼叫示例在这里:
allEngagementAreas(): Observable<IBaseEngagement[]> {
const url = `${this.baseURL}/${ENDPOINTS.engagementAreas}`;
return this.http.get(url).map(res => res.json() as IBaseEngagement[]);
}
我要在UI中显示的数组。
我该怎么办?
答案 0 :(得分:1)
您需要的是一种在API调用完成后让组件知道的方法。为此,您可以从服务中返回一个observable并将其订阅到组件中。
例如,在您的服务中,您可以:
public getOrgSubsidiaries(id) {
return this.organizationSubsidiaries(id).map(data => {
let subsdiaryNames = [];
// your logic
return subsdiaryNames;
});
}
然后,在组件内部,您可以执行以下操作:
ngOnInit(): void {
this.engagementService.getOrgSubsidiaries(id).subscribe(data => {
this.orgSubsidiaries = data;
});
}