在Angular Subscribe中使用回调?

时间:2018-06-03 21:17:08

标签: angular observable angular2-observables

这是在我的服务文件中。 我无法更改此功能代码,因为它被其他开发人员用于应用程序中的很多地方。正在使用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());

我想通过参数&#39; r&#39;对我的组件中的响应做一些事情。我是新观察者,所以我相信我在这里做错了..

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您实现的这个功能并没有真正扩展现有功能,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
    });

当然,如果这些回调已经是组件的实现方法,那么你可以用它们一行。

相关问题