【问题标题】:Using callbacks in Angular Subscribe?在 Angular 订阅中使用回调?
【发布时间】:2018-06-03 21:17:07
【问题描述】:

这是在我的服务文件中。 我无法更改此功能代码,因为其他开发人员在应用程序中的很多地方都使用了它。正在使用 HTTPclient。

getFieldDetailData(request?): Observable<any> {
        return this.http.get(this.apiBaseUrl + '/apiurl', { params: request })
            .catch(err => {
                err.statusmessage = 'fail';
                return err;
            });
    }

在同一个文件中,我正在编写这个用于回调的函数。

 testCallback(request, successFn, errorFn) {
        this.getFieldDetailData().
            subscribe(
                response => {
                    successFn(response);
                },
                error => {
                    errorFn();
                }
            );
    }

现在在我的组件文件中,我只想像这样在一行中传递参数以及成功和错误方法。

this.service.testCallback.subscribe(this.request, this.success(r), this.error());

我想对我的组件中返回的带有参数“r”的响应做一些事情。我是 observables 的新手,所以我相信我在这里做错了..

【问题讨论】:

  • 像这样传递它们this.service.testCallback(this.request, this.success, this.error)

标签: angular observable angular2-observables


【解决方案1】:

您不需要第二个功能。在您的组件中,您只需调用第一个函数并订阅它:

ngOnInit() {
    this.yourService.getFieldDetailData().subscribe(response => {
        // do something here with the response.
        // error handling should be done in side the catch() operator
    });
}

【讨论】:

    【解决方案2】:

    你实现的这个函数并没有真正扩展现有的功能,Rxjs 已经为你实现了这些处理程序。

    testCallback(request, successFn, errorFn) {
            this.getFieldDetailData().
                subscribe(
                    response => {
                        successFn(response);
                    },
                    error => {
                        errorFn();
                    }
                );
        }
    

    想象一下我们重写了这个函数,它看起来像这样(我们可以只使用原始的 getFieldDetailData 函数):

    testCallback(request) {
            return this.getFieldDetailData(request);
        }
    

    现在在您的组件中,您可以随意使用它:

    this.service.testCallback(request).subscribe(
        (r) => { // r will be the result of your request execution
            // your success callback code goes here
        }, 
        (error) => {
            // your exception handling goes here
        });
    

    当然,如果这些回调已经是你的组件实现的方法,你可以一行完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2019-04-12
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2019-02-12
      相关资源
      最近更新 更多