【问题标题】:Mergemap Observable which depends from previous gets ignored,with HTTPClient calls, Angular依赖于先前的 Mergemap Observable 被忽略,带有 HTTPClient 调用,Angular
【发布时间】:2021-05-21 07:20:11
【问题描述】:

我想从服务中执行三个函数作为 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 的调试错误是这个 'ERROR TypeError: Cannot read property '0' of undefined' 即使当我尝试在那里放置断点时从未访问过该函数(在 chrome 控制台上看到它))

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

【问题讨论】:

  • 这个过程对我来说很好。但是,你怎么知道订阅next 回调被忽略了呢?您是否检查了 HTTP 调用中的任何错误?尝试使用console.log 传递error 回调并查看它是否被打印出来。
  • 我进行了 chrome 调试并查看了哪些行已执行,哪些未执行。 (编辑:第一个 url 在调试时完美记录,第二个 url 也是如此,第三个(可能)给出此错误 'ERROR TypeError: Cannot read property '0' of undefined')
  • 在这种情况下,请检查 GetSecondUrl() 函数的输出。在尝试从其输出中访问第一个元素之前查看它是否已定义。
  • res2[0].thirdname 是我看到的这个错误的地方。它被定义,所有三个函数的工作方式完全相同,为什么第三个函数会出现问题是没有意义的。在这个函数中甚至看不到任何断点。
  • 试试this.nameService.GetSecondUrl(res1[0].secondname).pipe(tap(console.log))看看它的实际输出是什么。

标签: angular rxjs observable subscribe mergemap


【解决方案1】:

最终只使用 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"
        }
   ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2017-12-02
    • 2016-07-10
    • 1970-01-01
    相关资源
    最近更新 更多