在服务中调用函数时,我试图运行一个单独的函数。
这是一个简单的例子
foo() {
this.bar();
console.log('foo');
}
bar() {
console.log('bar');
}
运行我的代码版本时,我看到console.log('foo')工作正常,但没有成功
基本上,每次运行特定功能(A)时,我都需要触发另一个功能(B)来填充将在以后提取的数据,但是当我需要显示它时需要立即准备就绪。对于上下文,功能B将把数据保存到状态。
我被要求分享真实代码。在这里:
getMenuByHandoffType(locationID: number, handoffType: HandoffType): Observable<Menu> {
if (isNaN(locationID as any)) { // URL contains a slug
return this.cmsService.getSingleLocationBySlug(locationID.toString()).pipe(switchMap(locationInfo => {
return this.getMenuByHandoffType(Number(locationInfo.menu_id), handoffType);
}));
} else {
console.log('Getting Menu');
return this.apiService.getCategories(locationID).pipe(switchMap(pages => {
this.populateLeadThroughs(locationID).pipe(map(res => {
this.leadthroughs = res;
return
}));
const menu = this.mapping.categoriesToMenu(locationID, pages);
return this.contentService.getMenuWithImages(deMenu);
}));
}
}
populateLeadThroughs(siteID: number) {
const leads: any[] = [];
const order: Order = JSON.parse(sessionStorage.getItem('Order'));
return this.apiService.getLeadThroughs(siteID).pipe(map(leadthroughRes => {
leadthroughRes.forEach((leadThrough, index) => {
this.apiService.getLeadThroughItemsByGroupAndPickupTime(siteID, leadThrough.Id, order.orderReadyTimestamp).pipe(map(groupRes => {
leadThrough.Items = groupRes;
leads[leadThrough['Id']] = leadThrough;
console.log(leads);
}));
});
return leads;
}));
}
我也测试过:
this.leadthroughs = this.populateLeadthroughs(locationID);
我没有运气
答案 0 :(得分:0)
这里的问题是您使用该代码创建了一个可观察对象
this.populateLeadThroughs(locationID).pipe(map(res => {
this.leadthroughs = res;
return;
}));
您永远不会订阅它,因此它永远不会运行。我将您的代码更改为此:
getMenuByHandoffType(locationID: number, handoffType: HandoffType): Observable<Menu> {
if (isNaN(locationID as any)) { // URL contains a slug
return this.cmsService.getSingleLocationBySlug(locationID.toString()).pipe(switchMap(locationInfo => {
return this.getMenuByHandoffType(Number(locationInfo.menu_id), handoffType);
}));
} else {
console.log('Getting Menu');
return this.apiService.getCategories(locationID).pipe(
switchMap(pages => {
this.populateLeadThroughs(locationID).subscribe(res =>
{
this.leadthroughs = res;
});
const menu = this.mapping.categoriesToMenu(locationID, pages);
return this.contentService.getMenuWithImages(deMenu);
}));
}
}
populateLeadThroughs(siteID: number) {
const leads: any[] = [];
const order: Order = JSON.parse(sessionStorage.getItem('Order'));
return this.apiService.getLeadThroughs(siteID).pipe(map(leadthroughRes => {
leadthroughRes.forEach((leadThrough, index) => {
this.apiService.getLeadThroughItemsByGroupAndPickupTime(siteID, leadThrough.Id, order.orderReadyTimestamp).pipe(map(groupRes => {
leadThrough.Items = groupRes;
leads[leadThrough['Id']] = leadThrough;
console.log(leads);
}));
});
return leads;
}));
}
但是要小心,如果您观察不到并不会自动取消订阅(自动取消订阅通常仅在Http调用中发生),则您必须自行取消订阅。