如何解决无法在Springboot中调用put端点
我从前端(角度)获得此代码
private _baseUrl = "http://localhost:8080/api/v1/professor/";
getProfessor(id: string): Observable<Professor> {
const professor = this.http.get<Professor>(this._baseUrl + id);
return professor;
}
addProfessorrating(id: string,rating: Object): void {
// get the professor,then modify the ratings of them,and make a put request
this.getProfessor(id).subscribe(professor => {
let ratings = professor['ratings'];
ratings.push(rating);
professor['ratings'] = ratings;
return this.http.put<void>(this._baseUrl + id,professor,{
headers: new HttpHeaders({
'content-type': 'application/json'
})
})
});
}
该端点来自后端(春季启动):
@PutMapping(path = "/{id}")
public String updateProf(@PathVariable("id") String id,@Valid @NotNull @RequestBody Professor professor) {
logger.info("updating professor");
professorService.updateProfessor(id,professor);
return "Updated professor with id: " + id;
}
但是,端点未调用,因为记录器未在控制台中记录任何内容。我尝试了Postman,它确实调用了端点。我做错什么了吗,如果这篇文章不够具体,我也会提供任何信息。
更新:我通过Angular形式的onSubmit函数调用了addProfessorrating:
onSubmit(rating: Object) {
const id = this.route.snapshot.paramMap.get('id');
this.professorService.addProfessorrating(id,rating);
}
我将不胜感激。
解决方法
您需要使用RxJS高阶映射运算符(例如switchMap
)从一个可观察的(this.getProfessor()
)映射到另一个(this.http.put()
)。
尝试以下
private _baseUrl = "http://localhost:8080/api/v1/professor/";
addProfessorRating(id: string,rating: Object): void {
this.getProfessor(id).pipe( // get the professor,then modify the ratings of them,and make a put request
switchMap(professor => {
let ratings = professor['ratings'];
ratings.push(rating);
professor['ratings'] = ratings;
return this.http.put < void > (this._baseUrl + id,professor,{
headers: new HttpHeaders({
'content-type': 'application/json'
})
});
})
).subscribe(
res => console.log(res),err => console.log(err)
);
}
优良作法是从所有函数返回可观察值,并在基本函数中进行订阅。这样,您就可以保留调用的异步性质,并使用可观察对象发出的值。
addProfessorRating(id: string,rating: Object): Observable<any> { // <-- return the observable
return this.getProfessor(id).pipe( // get the professor,{
headers: new HttpHeaders({
'content-type': 'application/json'
})
});
})
); // <-- don't subscribe yet
}
onSubmit(rating: Object) {
const id = this.route.snapshot.paramMap.get('id');
this.professorService.addProfessorRating(id,rating).subscribe( // <-- subscribe here
res => {
console.log(res);
// other statements that depend on `res`
},err => {
// also good practice to handle error notifications from HTTP observables
}
);
}
其他类型的RxJS高阶映射运算符为mergeMap
,concatMap
和exhaustMap
。您可以发现它们之间here的简短区别。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。