如何等待直到我收到Angular 7中后端Spring Boot API的响应 [英] How to wait till i get a response from backend spring boot api in angular 7
问题描述
我想使用http post方法的结果从一条路线导航到另一条路线.但是导航是在没有http帖子的响应的情况下进行的.当我调试代码时,响应会越来越晚
I wanted to navigate from one route to another route with the result of http post method. But the navigation is happening without the response from http post. The response is getting later when i debugged the code
我该如何解决?有什么方法可以等待执行,直到响应来自后端?
How can i fix this ? is there any way to wait the execution till the response comes from backend ?
当我单击一个按钮时,将执行一个函数,并且将进行一次http发布调用,然后我需要将响应从发布请求传递到新路线
when i click on a button, a function will execute and a http post call will happen then i need to pass the response from the post request to a new route
Quiz.service.ts
Quiz.service.ts
getResult(answers: QuestionAnswer): Observable<number> {
return this.http.post<number>(`${this.API_URL}result`, answers);
}
exam.component.ts
exam.component.ts
submitQuiz() {
this.isSubmitted = true;
const answers: QuestionAnswer = new QuestionAnswer(Array.from(this.selectedAnswers.keys()), Array.from(this.selectedAnswers.values()));
let result: number;
this.quizService.getResult(answers).subscribe(data => {
console.log(data);
result = data;
});
console.log(result);
this.navigateToResult(result);
}
navigateToResult(result: number) {
if(result != undefined){
const navigationExtras: NavigationExtras = {
queryParams: {
"result" : JSON.stringify(result)
}
}
this.router.navigate(['result'], navigationExtras);
}
}
未定义的值传递到路由中
the value undefined is passed into the route
推荐答案
从getResult()
方法返回可观察值是异步操作.因此,您编写的初始代码块将失败,因为此时result
将是未定义的.为了进一步了解这一点,您应该阅读JavaScript的事件循环.
The returning of the observable value from getResult()
method is an asynchronous operation. Because of that, the initial block of code you have written will fail as result
will be undefined at that point. To further understand this, you should read up on JavaScript's event loop.
您应该改为执行此操作-基本上,您可以处理subscribe块中的路由,以便仅在完成订阅后才调用该路由.这样,result
将包含一个值(而不是未定义的),并且navigateToResult()
将被成功执行,因为它提供了有效的参数.
You should do this instead - basically, you handle the routing within the subscribe block such that it will only be called after the subscription has been completed. This way, result
will contain a value (instead of being undefined), and navigateToResult()
will be successfully executed since it is supplied with a valid parameter.
submitQuiz() {
this.isSubmitted = true;
const answers: QuestionAnswer = new QuestionAnswer(Array.from(this.selectedAnswers.keys()), Array.from(this.selectedAnswers.values()));
let result: number;
this.quizService.getResult(answers).subscribe(data => {
result = data;
console.log(result);
this.navigateToResult(result);
});
}
这篇关于如何等待直到我收到Angular 7中后端Spring Boot API的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!