-2

In my service.ts file i have the following method :

 postFiltersAndSearch(param: someType) : boolean{
    let test : boolean
    //this.bsSearchFilter.next(param)
    this.http.post<any[]>(environment.ApiUrl + 'controller/method/', param,this.tokenService.addCors()).subscribe(x => {
    if(x.length==0){
      //do something...
    }
    //this.bsSearchResult.next(x)
    }, error => { 
      console.log(error)
      test = false
    } , ()=> {
      console.log()
      test = true
    })

    return test
  }

In my other component.ts file i am calling this method like so :

let result= this.searchService.postFiltersAndSearch(someParam)

The problem is my service method always jumps to the final return test before evaluating the results either from the complete or error bloc of the post request and therefore i have undefined as the result of calling this function.

Is there a way around i can wait for the evaluation of the results before quickly reaching the final return test ?

MarloIsh
  • 53
  • 5
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Nov 25 '21 at 14:21
  • @R.Richards no i am still getting undefined as a result in my calling instruction – MarloIsh Nov 25 '21 at 14:36

1 Answers1

0

return test is sync code , instead http request is async , so you return boolea before the response of request, you need to use all as observable, waiting for response and then evaluate value.

you should use something like this.

postFiltersAndSearch(param: someType) : boolean{
     
    //this.bsSearchFilter.next(param)
    return this.http.post<any[]>(environment.ApiUrl + 'controller/method/', param,this.tokenService.addCors())
.pipe(
tap(x => {
if(x.length==0){
      //do something...
    }
    //this.bsSearchResult.next(x)
}),
map(()=> true), // map observable to boolean value true 
catchError(e => {
  return of(false);  // of is e method to create observable of specific value
})
);

then, in other place where you use it

this.searchService.postFiltersAndSearch(someParam)
.subscribe(x => {
   if(!!x){ 
// return true value
   } else { 
//return false value
   }
)

You can use async/await too, search on google about it.