无需订阅调用类即可获取可观察的返回值 [英] Get observable return value without subscribing in calling class

查看:39
本文介绍了无需订阅调用类即可获取可观察的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript/Angular 中,您通常会调用一个函数,该函数返回一个 observable 并在这样的组件中订阅它:

In TypeScript / Angular, you would usually call a function that returns an observable and subscribe to it in a component like this:

this.productsService.getProduct().subscribe((product) => { this.product = product });

当代码在管理数据的类中运行时,这很好,但在我看来,这不应该在组件中处理.我可能错了,但我认为组件的工作应该是请求和显示数据而不处理它是如何检索的.

This is fine when the code runs in a class that manages data, but in my opinion this should not be handled in the component. I may be wrong but i think the job of a component should be to ask for and display data without handling how the it is retrieved.

在 angular 模板中,您可以这样做以订阅并显示可观察的结果:

In the angular template you can do this to subscribe to and display the result of an observable:

<h1>{{ product.title | async }}</h1>

组件类中可以有这样的东西吗?我的组件显示一个表单并在输入后检查日期是否有效.提交表单被阻止,直到该值有效,我想将其背后的所有逻辑保留在应订阅 AJAX 调用的服务中,该组件仅检查它是否获得了有效日期.

Is it possible to have something like this in the component class? My component displays a form and checks if a date is valid after input. Submitting the form is blocked until the value is valid and i want to keep all the logic behind it in the service which should subscribe to the AJAX call, the component only checks if it got a valid date.

 class FormComponent {
    datechangeCallback(date) {
        this.dateIsValid$ = this.dateService.checkDate(date);
    }

    submit() {
        if (this.dateIsValid$ === true) {
            // handle form submission...
        }
    }
}

推荐答案

您可以将 rxjs Observables 转换为 ES6 Promises,然后使用 async-await 语法来获取没有 observable 订阅的数据.

You can convert rxjs Observables to ES6 Promises and then use the async-await syntax to get the data without observable subscription.

服务:

export class DateService {
  constructor(private http: HttpClient) {}

  async isDateValid(date): Promise<boolean> {
    let data = await this.http.post(url, date, httpOptions).toPromise();
    let isValid: boolean;
    // perform your validation and logic below and store the result in isValid variable
    return isValid;
  }
}

组件:

class FormComponent {
    async datechangeCallback(date) {
        this.dateIsValid = await this.dateService.isDateValid(date);
    }

    submit() {
        if (this.dateIsValid) {
            // handle form submission...
        }
    }
}

附注:

如果这是一个简单的 HTTP 请求,它在接收到一个值时完成,那么使用 Promises 不会有什么坏处.但是如果这个 obersvable 产生一些连续的值流,那么使用 Promises 不是最好的解决方案,你必须恢复到 rxjs observables.

If this is a simple HTTP request, which completes on receiving one value, then using Promises won't hurt. But if this obersvable produces some continuous stream of values, then using Promises isn't the best solution and you have to revert back to rxjs observables.

这篇关于无需订阅调用类即可获取可观察的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆