Eldho
Eldho

Reputation: 8301

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

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

Upvotes: 4

Views: 9892

Answers (5)

cpr43
cpr43

Reputation: 3112

We have another action parameter in subscribe() after er action that will help you to return without using observable.

  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') {
          issuccess = false;
        } else {
          issuccess = true;
        }
      },
        (er) => {

          issuccess = false;
        },
     () => {return issuccess });
    }

Subsribe 3 paramters

subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): 

Upvotes: 1

David
David

Reputation: 34475

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

Upvotes: 4

MartinZyk
MartinZyk

Reputation: 192

try it like

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 async save() {
 let issuccess = false;

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

      return issuccess = false;
    });
      return issuccess ;
}

Upvotes: 1

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38713

In this case you can use promise instead of subscribe. But while binding the data into html, then you should go with async pipe

So, your service would be like

 AddParty(newUserObject) {
        return this.http.post(url)
            .toPromise().then(responce => <any[]>responce.json())
            .catch(error => {
                return error;
            });
    }

and retrieve that looks like

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

                return issuccess = false;
            });
    }

Upvotes: 1

DeborahK
DeborahK

Reputation: 60626

How about something like this:

public SaveItem() {
 const isNew = false;
 save(isNew)
}

public SaveAndNew() {
 const isNew = true;
 save(isNew)
}


private save(isNew) {

 this.myservice.AddParty(newUserObject)
  .subscribe(data => {   
    if (data['status'].toString() === '1') {
      saveComplete(isNew);
    } else {
      saveFailed(isNew)
    }
  },
    (er) => {
      saveFailed(isNew)
    });
}

saveComplete(isNew) {
  // Check isNew as needed.
  // Close dialog or whatever
}

saveFailed(isNew) {
  // do whatever here
}

Or ... TypeScript now supports async/await ... so you could consider using them here. See this for more information: https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

Upvotes: 2

Related Questions