等待POST完成,然后切换到PUT



我正在努力寻找问题的解决方案:我正在做一个";调查";模块,您可以在其中回答一些问题。但问题在于";回答";内容。假设您有一个输入字段,在每次输入时张贴您的答案,并且在第一次张贴后,需要根据POST返回的id进行PUT。

到目前为止我所拥有的:(这只是一个例子,所以有些地方可能不正确,但问题仍然相同(

@Component({
selector: 'app-answer',
template: '<input [(ngModel)]="answer.text" (ngModelChange)="change()">',
})
export class AnswerNgmodelComponent {
answer: Answer = { id: 0, text: '' };
private answerChanged = new Subject<string>();
constructor(private http: HttpClient) {
this.answerChanged
.pipe(
debounceTime(1000),
switchMap((res) =>
this.answer.id > 0
? this.updateAnswer(this.answer)
: this.postAnswer(this.answer)
)
)
.subscribe((res) => {
if(res) {
this.answer.id = res;
}
});
}
change() {
this.answerChanged.next();
}
//Returns id of created answer
postAnswer(answer: Answer): Observable<number> {
return this.http.post<number>('http://api.com/answer', answer);
}
//Updates answer
updateAnswer(answer: Answer): Observable<any> {
return this.http.put('http://api.com/answer/' + answer.id, answer);
}
}
export class Answer {
id: number;
text: string;
}

我遇到的问题:第一次回答问题时,我们需要等待帖子完成并设置答案的id。但是,如果邮件请求有点延迟,那么就有一个窗口,你可以"更新";你的答案,当它还没有完成张贴,并将再次张贴答案。

我怎么能等";创建";张贴完成,然后开始";"更新";之后

更新显然,这就像将switchMap更改为concatMap一样简单-多亏了@akotech

您可以保存请求订阅并在新请求之前取消订阅(如果存在(,这将取消活动请求。

@Component({
selector: 'app-answer',
template: '<input [(ngModel)]="answer.text" (ngModelChange)="change()">',
})
export class AnswerNgmodelComponent {
answer: Answer = { id: 0, text: '' };
private answerChanged = new Subject<string>();
private activeRequestSubscription: Subscription = null;
constructor(private http: HttpClient) {
this.answerChanged
.pipe(
debounceTime(1000),
switchMap((res) =>
this.answer.id > 0
? this.updateAnswer(this.answer)
: this.postAnswer(this.answer)
)
)
.subscribe((res) => {
if(res) {
this.answer.id = res;
}
});
}
change() {
this.answerChanged.next();
}
//Returns id of created answer
postAnswer(answer: Answer): Observable<number> {
this.activeRequestSubscription?.unsubscribe();
this.activeRequestSubscription = this.http.post<number>('http://api.com/answer', answer);
return this.activeRequestSubscription;
}
//Updates answer
updateAnswer(answer: Answer): Observable<any> {
this.activeRequestSubscription?.unsubscribe();
this.activeRequestSubscription = this.http.put('http://api.com/answer/' + answer.id, answer);
return this.activeRequestSubscription;
}
}
export class Answer {
id: number;
text: string;
}

我建议您使用服务来管理http请求。

仅使用post请求并维护id当您第一次点击post请求时,您传递了id:0之后,您将有一个id进行更新然后您可以在post数据中传递id所以简单地说,如果你的id=0,就意味着你在特定的调查中第一次回答。如果你有任何来自后端的id,你可以在数据中传递该id,并更新现有的池

示例:

  1. 当您第一次回答时:您的req数据:
    let reqData = {
    id: 0,
    content: 'test',
    des: 'test'
    }
    
  2. 当您更新您的答案库时:您的req数据:
    let reqData = {
    id: 112,   
    content: 'test',
    des: 'test'
    }
    

注意:id 112由您的后端生成

相关内容

最新更新