【问题标题】:How does Observables work in Angular 2Observables 如何在 Angular 2 中工作
【发布时间】:2017-01-30 21:28:30
【问题描述】:

我正试图围绕可观察对象在 Angular 2 中的工作方式而不是仅仅将它们用作模式。如果我像下面这样创建一个基本的 observable,我可以在源变量上调用 subscribe 方法,该变量是由于创建 observable 并将其分配给源变量而存在的。

let numbers = [19, 38, 57];
let source = Observable.from(numbers);

source.subscribe(
  value => console.log(`value: ${value}`),
  error => console.log(`error: ${error}`),
  () => console.log('complete')
);

在 Angular 2 中,我有以下代码:

组件:

private getDevicesByUserId(): void {
  this.devicesHttp.getDevicesByUserId(this.userID)
    .subscribe(
      data => {
        this.devices = data;
      },
      error => {},
      () => {}
    );
}

HTTP 服务:

public getDevicesByUserId(userID: number): Observable<any> {
  return this.http.get(this.url + 'api/device/user/' + userID, {
    headers: this.httpHeaders.getHeaders()
  })
  .map((response) => this.handleData(response))
  .catch((error) => this.handleError(error));
}

在上面的模式中,我在 getDevicesByUserId 函数上调用 subscribe 方法,但在 http 中没有创建 observable。也许我遗漏了一些东西,但它只是一个返回 http 调用结果的函数。我怎样才能在这样的常规函数​​上调用订阅方法?如果我没有创建可观察对象,该函数甚至如何具有此属性?

【问题讨论】:

    标签: angular


    【解决方案1】:

    用于getpost 的Angular 2 Http service 函数内置返回一个冷的Observable,它返回一个响应。

    您不必显式创建 Observable。如果您愿意,可以通过 http 代码here

    作为冷可观察对象,请求本身在观察者订阅时发送。 更多关于hot and cold observable here 您自己服务中的 getDevicesByUserId 返回您最终在组件中订阅的相同 observable。

    希望这能解决问题。

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多