gpt4 book ai didi

angular - 有条件请求作为序列中的第一个请求

转载 作者:行者123 更新时间:2023-12-02 19:55:26 25 4
gpt4 key购买 nike

我正在尝试在 rxjs 中发送请求,如果用户已上传文件,则该请求是有条件的。之后,如果文件在那里,我将其附加到发送的用户对象,然后我需要在发布到文件端点后修补用户。

我遇到的问题是,因为它在第一个请求中处于 if 条件,所以我知道我无法订阅它。我可以通过执行 if { } else { } 来解决这个问题,这是我试图避免的。

这就是它的样子。

if (fileSelected) {
this.dataService.type('files').post(fileSelected).subscribe((response) => {
this.user.file = response;

// I need to then post the updated user to the patch endpoint.
});
}

this.dataService.type('users').patch(this.user).subscribe(() => {

});

显然在上面的示例中(我当前的做法)它不会等待第一个请求完成。我知道我可能可以使用 .pipe 并将某些内容通过管道传输到末尾,但正如我之前所说,由于这是第一个请求,我不完全确定这是如何完成的。

最佳答案

您想要使用 fileSelected 的值启动一个可观察流,然后有条件地切换到其他流。

const user$ = of(fileSelected).pipe(
switchMap(selected => selected
? this.dataService.type('files').post(fileSelected)
: of(undefined)
),
switchMap(response => {
this.user.file = response; // will be undefined if not selected
return this.dataService.type('users').patch(this.user);
})
);

user$.subscribe(value => console.log(value));

您还可以使其与用户对象更加相关,这样您就不会从函数式编程内部引用 this.user 属性。这更接近使其成为可重用的 RxJS 运算符。

function sendFiles(user, fileSelected): Observable<any> {
return of(user).pipe(
switchMap(user => {
const send$ = fileSelected ? this.dataService.type('files').post(fileSelected) : of(undefined);
return send$.pipe(map(response => (user.file = response, user)));
),
switchMap(user => this.dataService.type('users').patch(user))
);
}

sendFiles(this.user, fileSelected).subscribe(value => console.log(value));

或者也许更简单:

function sendFiles(user: User, fileSelected: boolean, {type}: DataService): Observable<any> {
const send$ = fileSelected ? type('files').post(fileSelected) : of(undefined);
return send$.pipe(
map(file => ({...user, file})),
switchMap(user => type('users').patch(user))
);
}

关于angular - 有条件请求作为序列中的第一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com