Angular: 如何从 httpClient 请求中获取参数并在循环相同的请求中使用
Angular: How to get parameter from httpClient request and use in looping over the same request
所以我有一个方法可以通过服务器的 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 发送,我该如何解决这个问题?
问题很可能是您订阅了这个功能:
this.getNodeById(this.parentId)
x arr.length
倍真快。
然后您的值才会到达,所有值都用于相同的 ID。
最适合您的解决方案是使用 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)
所以我有一个方法可以通过服务器的 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 发送,我该如何解决这个问题?
问题很可能是您订阅了这个功能:
this.getNodeById(this.parentId)
x arr.length
倍真快。
然后您的值才会到达,所有值都用于相同的 ID。
最适合您的解决方案是使用 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)