依赖于先前的 Mergemap Observable 被忽略,使用 HTTPClient 调用,Angular

问题描述

我想从一个服务中执行三个函数作为 Observables 来传递数据,直到最后一个一个组件使用 MergeMap 方法订阅它们,但最后一个函数甚至没有被访问。

服务是这样工作的:

public GetFirstUrl(firstname: string): Observable<FirstValue[]>{
   const url = 'https://graph.microsoft.com/v1.0/groups/'+firstname+'/events';
   return this.http.get<First>(url).pipe(map(.........)) (etc.)
}

public GetSecondUrl(secondname: string): Observable<SecondValue[]>{
   const url = 'https://graph.microsoft.com/v1.0/groups/'+secondname+'/events';
   return this.http.get<Second>(url).pipe(map(.........)) (etc.)
}

//this third method is never accessed
public GetThirdUrl(thirdname: string): Observable<ThirdValue[]>{ 
   const url = 'https://graph.microsoft.com/v1.0/groups/'+thirdname+'/events';
   return this.http.get<Third>(url).pipe(map(.........)) (etc.)
}

并且尝试访问这些链接的组件的工作方式如下:

ngOnInit(): void {
    this.nameService.GetFirstUrl('TestName1').pipe(
          mergeMap((res1) => this.nameService.GetSecondUrl(res1[0].secondname)),mergeMap((res2) => this.nameService.GetThirdUrl(res2[0].thirdname))
        ).subscribe((res3) => {
          const FinalValue = res3; // this line is ignored
        });
}

为什么这种方法行不通?是不是因为异步程序以一种奇怪的方式一个一个地传递数据?

(来自最后一个 url 的调试错误是这个“错误类型错误:无法读取未定义的属性“0”,即使我尝试在那里放置断点时从未访问过该函数(在 chrome 控制台上看到它))

(编辑:使用 concatmap,仍然是同样的问题。res1[0].secondname 未定义,因此导致未定义的 res2[0].thirdname)

解决方法

最终只使用 concatMap 作为一种方法,我在我的模型中发现了一个错字,它应该与 Graph 中的 http 调用“值”完全相同。解决了!

ngOnInit(): void {
    this.nameService.GetFirstUrl('TestName1').pipe(
          concatMap((res1) => this.nameService.GetSecondUrl(res1[0].secondname)),concatMap((res2) => this.nameService.GetThirdUrl(res2[0].thirdname))
        ).subscribe((res3) => {
          const FinalValue = res3; // this line is ignored
        });
}
export interface PlannerPlans{
    value: PlannerPlansValue[]; // this should be named exactly value,not val or anything different
}

之前与此不匹配

{
"value": [
        {
            "id": "ExampleIdFNBNEGAIBGNAGVKGOE"
        }
   ]
}