从订阅打字稿返回值

Posted

技术标签:

【中文标题】从订阅打字稿返回值【英文标题】:Returning value from subscription typescript 【发布时间】:2018-07-30 11:49:38 【问题描述】:

我如何从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,它将始终返回一个错误值。

我将如何等待保存功能并根据响应返回特定值?

我读过关于回调的文章,它似乎并不优雅,有没有优雅的方法来做到这一点

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

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

var isSuccess = await SaveAsync(party);

【问题讨论】:

你可以转换成一个promise.. 【参考方案1】:

在这种情况下,您可以使用promise 而不是subscribe。但是在将数据绑定到 html 时,你应该使用async pipe

所以,你的服务会是这样的

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

并检索看起来像

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

                return issuccess = false;
            );
    

【讨论】:

转向承诺对我来说不是一个选择,我的大部分代码都是订阅模式。感谢您的选择【参考方案2】:

这样的事情怎么样:

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

或者 ... TypeScript 现在支持 async/await ... 所以你可以考虑在这里使用它们。更多信息请参见:https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

【讨论】:

【参考方案3】:

你可以让你的保存方法返回一个可观察的布尔值

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

【讨论】:

有错误说 save `'Property 'subscribe' does not exist on type '() => Observable'` 我编辑了我的帖子,应该是 this.save() 而不是 this.save 不是因为它, 它返回的不是可观察的承诺 对不起,什么是返回承诺?【参考方案4】:

试试看

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

我们在 subscribe() 中在 er 操作之后有另一个操作参数,可以帮助您在不使用 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 );
    

订阅 3 个参数

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

【讨论】:

里面用的是什么操作符,有没有文档

以上是关于从订阅打字稿返回值的主要内容,如果未能解决你的问题,请参考以下文章

具有默认参数值的打字稿条件返回类型

打字稿。为啥功能接口中描述的“返回值”类型没有严格执行?

打字稿返回类型(布尔值 vs 'is' vs <nothing>)差异? [复制]

打字稿方法返回未定义?

打字稿通用承诺返回类型

两个数组之间的打字稿差异