从Angular函数返回的值



我正在尝试连接到我的应用程序的后端,但我想显示一个零食栏与我收到的响应,但是当我调用端点负责的动作我不能得到响应,如果它是正确的或不,从后面如果我得到它,在端点如果我有响应,但在我调用它的函数我没有得到它。

我有一个函数如下,它被一个按钮调用

<<p>按钮功能/strong>
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
});
}

从服务返回订阅是不好的做法(就像在组件中存储端点一样)。

我猜这个变体可以为你工作:

服务:

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']))
}

当你不再需要订阅时,不要忘记取消订阅,以防止内存泄漏。在这种情况下,你只需要一次发射,所以我在这里添加了&;take(1)&;管道。

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']);
});

}

最新更新