我从前端(角度)获得此代码
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);
}
我将不胜感激。
答案 0 :(得分:2)
您需要使用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, 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'
})
});
})
); // <-- 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的简短区别。