我正在嘗試在我的應用程式中建立與后端的連接,但我想顯示一個帶有我收到的回應的小吃欄,但是當我呼叫負責該操作的端點時,如果它正確與否,我無法得到回應,如果我得到它,則從后面開始,如果我有回應,則在端點中,但是在我呼叫它的函式中,我沒有得到它。
我的功能如下,它是由一個按鈕呼叫的
按鈕功能
sendData(data:any, endPoint:any){
console.log(this.dataService.postForm(data,endPoint))
** I want to get the response here, but i got "undefined"
}
端點:
postForm(dataPost:any, endPointValue:any){
this.http.post<any>(`${this.BASE_URL}${endPointValue}/`, dataPost).subscribe((response) => {
console.log(response)
this.router.navigate(['main']);
}, err => {
alert("404")
this.router.navigate(['main']);
});
}
這是我想做的事情
postForm(dataPost:any, endPointValue:any){
this.http.post<any>(`${this.BASE_URL}${endPointValue}/`, dataPost).subscribe((response) => {
console.log(response)
this.router.navigate(['main']); *This is not working too
return response ** I want to catch this response
}, err => {
alert("404")
this.router.navigate(['main']); *This is working
});
}
uj5u.com熱心網友回復:
從服務回傳訂閱是不好的做法(就像將端點存盤在組件中一樣)。
我想這個變體可以為你作業:
服務:
postForm(postDTO: any): Observable<any> {
this.http.post<any>(`${this.BASE_URL}/your_endpoint_path`, postDTO)
}
零件:
sendData(data: any) {
this.dataService.postForm(data).pipe(
take(1),
tap(console.log),
catchError(err => alert(err.message))
)
.subscribe(_ => this.router.navigate(['main']))
}
當您不再需要它們時,不要忘記取消訂閱每個訂閱,以防止記憶體泄漏。在這種情況下,您只需要 1 個發射,所以我在這里添加了“ take(1) ”管道。
uj5u.com熱心網友回復:
postForm(dataPost:any, endPointValue:any){
this.http.post<any>(`${this.BASE_URL}${endPointValue}/`, dataPost).subscribe((response) => {
console.log(response)
this.router.navigate(['main']).then(()=>{
return response;
});
}, err => {
alert("404")
this.router.navigate(['main']);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480915.html
