从订阅打字稿中返回值

时间:2018-02-20 07:21:40

标签: angular typescript rxjs angular2-observables

我如何从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);

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

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

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 :(得分: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;
            });
    }

答案 3 :(得分:1)

尝试像

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

答案 4 :(得分:1)

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