首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Angular订阅中使用回调?

在Angular订阅中使用回调?
EN

Stack Overflow用户
提问于 2018-06-04 05:17:08
回答 2查看 3.3K关注 0票数 0

这在我的服务文件中。我不能更改这个函数代码,因为它在应用程序中被其他开发人员使用了很多地方。正在使用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‘的响应做一些处理。我是第一次接触可观察对象,所以我认为我在这里做错了什么。

EN

回答 2

Stack Overflow用户

发布于 2018-06-04 05:56:38

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

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

Stack Overflow用户

发布于 2018-06-06 20:36:28

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

当然,如果这些回调已经是组件的已实现方法,那么您可以执行一行操作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50671053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档