【问题标题】:How to make sure that a function returns after an async block has been executed?如何确保在执行异步块后函数返回?
【发布时间】:2018-04-14 12:11:53
【问题描述】:

我正在使用 Angular 4.2.4 / RxJS 5.4.2,我正在尝试使用服务方法来检索一些数据并将该数据分配给我的组件中的属性:

组件:

ngOnInit() {
    this.componentProperty = this.myService.serviceMethod(someParameter);
}

服务:

serviceMethod(someParameter: someType) {

    let returnValue: anotherType;

    // getting the Observable involves using "someParameter"
    // (the code was simplified for the sake of clarity)
    someObservable.subscribe(
        data => { returnValue = data; }
    );

    return returnValue;    
}

问题是subscribe()里面的函数是异步执行的,所以方法总是返回undefined

关于如何解决这个问题的任何想法?一个特殊的 RxJS 方法?一些我不知道的花哨的 ES.next 关键字?另一个合乎逻辑的设计(保持 SoC 整洁)?

提前致谢!

【问题讨论】:

    标签: angular typescript asynchronous rxjs reactive-programming


    【解决方案1】:

    服务方法通常应该返回值是Observables 或Promises。

    Observables 的情况下,你会写类似

    serviceMethod(someParameter: someType) {
      return getSomeObservable(someParameter);
    }
    

    在你的服务中和类似的东西

    ngOnInit() {
      this.myService.serviceMethod(someParameter).subscribe(value => {
        this.componentProperty = value;
      });
    }
    

    在你的组件中使用它。

    【讨论】:

      【解决方案2】:

      把它锁起来。一个简单的方法:

      return someObservable.subscribe(
              data => { call the function you want }
          );
      

      【讨论】:

        猜你喜欢
        • 2015-10-22
        • 2020-03-13
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        相关资源
        最近更新 更多