Mahmoud Niypoo
Mahmoud Niypoo

Reputation: 1710

RXJS Convert Observable to boolean

Hello I'm trying to write function like this

 verify(){
    return this.http.post(environment.api+'recaptcha/verify',{
      token : this.token
    }).pipe(map(res=>res.json()));
  }

i want use it as boolean like

if(this.verfiy()) { do something}

how , Now i must subscript first and handle data

Upvotes: 2

Views: 4070

Answers (3)

Aragorn
Aragorn

Reputation: 5289

If you want verify function to subscribe and determine the boolean based on the http response, Subscribe inside your verify function instead of pipe..

verify(){
    this.http.post(environment.api+'recaptcha/verify',{
      token : this.token
    }).subscribe(res=> {

                        //do your logic to return boolean
                        return res.json();
                       });
  }

Upvotes: 0

frosty
frosty

Reputation: 21762

I would do something like this

verify(){
    return this.http.post(blah)
        .pipe(
            map((res: any) => res.json()),
            filter(json => json)
        );
}

The filter will only return if the json was not falsy.

So then you can do this:

service.verify().subscribe(()=>{
    // This code only will fire when the json was not falsy
    console.log("We verified it");
})

Upvotes: 0

rguerin
rguerin

Reputation: 2128

Since your HTTP call is asynchronous you will have to wait for its response. Try this:

this.verify().subscribe(
   res => {
       if (res) {
           // do something
       }
   }
)

Upvotes: 4

Related Questions