Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from subscription typescript

How would i return success from Save() method.

public SaveItem() {
 if(save()){ // The goal is to use save method like this
  // Close pop up;
}

public SaveAndNew() {
 if(save()){  // The goal is to use save method like this
  // Create new item;
}


private save() {
 let issuccess = false;

 this.myservice.AddParty(newUserObject)
  .subscribe(data => {   
    if (data['status'].toString() === '1') {
      return issuccess = false;
    } else {
      return issuccess = true;
    }
  },
    (er) => {

      return issuccess = false;
    });
}
  • If i have save(): boolean it will throw error that Must return a value if return issuccess outside the subscribe it will always return a false value.

How would i await the save function and return a specific value based on response ?

I have read about callbacks and its seems to be not elegant, Is there any elegant way to do this

callbacks-vs-promises-vs-rxjs-vs-async-awaits

If its a C# i would do this

var isSuccess = await SaveAsync(party);
like image 669
Eldho Avatar asked Oct 29 '25 14:10

Eldho


1 Answers

you can make your save method return an observable of boolean value

public SaveAndNew() {

this.save().subscribe(success =>
{
    if(success)
    {
      // Create new item;
    }
});

private save() : Observable<boolean> {

 return this.myservice
            .AddParty(newUserObject)
            .map(data=> data['status'].toString() === '1')
            .catch(err => Observable.of(false)); 
}
like image 77
David Avatar answered Oct 31 '25 03:10

David