从订阅打字稿返回值

从订阅打字稿返回值

本文介绍了从订阅打字稿返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Save()方法返回成功.

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

  • 如果我有save(): boolean,则会抛出错误,即Must return a value如果在订阅之外返回issuccess,则将始终返回错误值.
    • 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.
    • 我将如何等待保存功能并根据响应返回特定值?

      我已经阅读了有关回调的内容,但它似乎并不优雅,是否有任何优雅的方法可以做到这一点

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

      如果它是C#,我会这样做

      If its a C# i would do this

      var isSuccess = await SaveAsync(party);
      

      推荐答案

      您可以使save方法返回可观察到的布尔值

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

      这篇关于从订阅打字稿返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:21