Home > Software design >  Return value from Angular function
Return value from Angular function

Time:05-20

I am trying to make the connection to the backend in my application but I want to show a snackbar with the response I receive, but when I call the endpoint in charge of the action I can't get a response if it was correct or not, from the back if I get it and in the endpoint if I have the response but in my function where I call it I don't get it.

I have the function as follows and it is called by a button

button function

sendData(data:any, endPoint:any){
console.log(this.dataService.postForm(data,endPoint))
** I want to get the response here, but i got "undefined" 

}

Endpoint:

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

This is something that i want to do

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

CodePudding user response:

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

}

CodePudding user response:

It's bad practice to return a Subscription from a Service (just like storing an endpoint in a component).

I guess this variant can work for you:

Service:

postForm(postDTO: any): Observable<any> {
  this.http.post<any>(`${this.BASE_URL}/your_endpoint_path`, postDTO)
}

Component:

sendData(data: any) {
  this.dataService.postForm(data).pipe(
    take(1),
    tap(console.log),
    catchError(err => alert(err.message))
  )
  .subscribe(_ => this.router.navigate(['main']))
}

Also don't forget to unsubscribe from every subscription when you don't need them anymore, to prevent memory leaks. In this case you need only 1 emission, so I added here "take(1)" pipe.

  • Related