【问题标题】:Angular: How to get parameter from httpClient request and use in looping over the same requestAngular:如何从 httpClient 请求中获取参数并用于循环相同的请求
【发布时间】:2021-10-22 23:02:47
【问题描述】:

所以我有一种方法可以通过服务器的 id 获取树父节点

getParentById(id:string):return httpClient

我想循环这个方法并获取从这个调用返回的 parentId 并将其作为参数放回去以获取子项, 我只有第一个 parentId,所以我在第一次调用时传递它;

this.parentId ='123'

for(let i =0;i<arr.length;i++){
   this.getNodeById(this.parentId).subscribe(res =>{

     this.parentId = res.parentId; 

    // I am trying to append the parent id I have, so in the next iteration of th loop, the 
      parent id is updated
  })
}

问题是第一个 parentId 值没有改变,所有请求都使用相同的 parentId 发送,我该如何解决这个问题?

【问题讨论】:

  • 谢谢你的解释,我是编码新手,所以我只是谈谈我正在使用的东西,无论如何,有没有常见的解决方法来处理这种情况?

标签: angular rxjs httpclient


【解决方案1】:

对你来说最好的解决方案是使用 EXPAND,一个用于递归调用的 rxjs 运算符

import { from, EMPTY } from 'rxjs';
import { expand, tap} from 'rxjs/operators';

this.getNodeById(this.parentId).pipe(
  tap(res => {
      // do something on success
 }),
 expand((res) => res.parentId  // call getNodeById if you have a parentId otherwise return EMPTY
     ? this.getNodeById(res.parentId)
     : EMPTY;
 )
 ).subscribe(console.log)

【讨论】:

  • 哦,谢谢,这正是我要找的
【解决方案2】:

问题很可能是你订阅了这个函数:

this.getNodeById(this.parentId)

x arr.length 次非常快。

只有这样你的值才会到达,都是同一个 id。

【讨论】:

  • 那么我怎样才能使它工作,例如,如果只有当前请求得到它,是否有一种方法可以执行下一个请求?
  • 看看this question
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多