Returning value from subscription typescript

只谈情不闲聊 提交于 2019-12-21 05:43:07

问题


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

回答1:


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



回答2:


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




回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/48879798/returning-value-from-subscription-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!