【发布时间】:2019-02-06 18:43:55
【问题描述】:
我在 angular2 中围绕 observables 和订阅时遇到了真正的麻烦。我目前遇到的问题如下:
我有一项服务,其中包含从 API 发布和获取数据的方法。服务被注入到一个组件中,该组件直接调用服务中的那些方法。该服务然后检索数据并自行存储,但我想在组件中处理该数据。在服务本身检索和存储数据后,我无法弄清楚如何让组件执行功能。
service.ts
import { Injectable } from 'angular2/core';
import { Http } from 'angular2/router';
@Injectable()
export class Service {
result: Object;
constructor(http: Http) {
this.http = http;
}
httpGet(url) {
return this.http.get(url).subscribe(
result => this.result = result.json(),
error => console.log(error),
() => {}
)
}
}
组件.ts
import { Component } from 'angular2/core';
import { Service } from './service';
@Component({
...
})
export class Component {
formattedResult: Object;
constructor(service: Service) {
this.service = service;
this.service.httpGet('/api')
// How do I call format result on service.result only after it is completed?
this.formatResult(service.result) // Need to execute this after the http call is completed
// I want something like:
this.service.httpGet('/api').then(() => formatResult(this.service.result));
}
formatResult(result) {
this.formattedResult = result.map(x => x.length) // For example
}
}
【问题讨论】:
-
@GünterZöchbauer 谢谢,它关闭了,但我想在服务中保留一个 .subscribe ,因为它自己存储该信息以供以后访问。一个 http.get 上不可能有两个 .subscribe(它会调用它两次)。除非接受的设计模式是仅在组件中使用 .subscribe 并从组件中显式设置服务变量?我只想保持服务和组件逻辑分离。
-
stackoverflow.com/a/34405243/215945 - 使用
flatMap()回答链可观察对象。
标签: angular asynchronous rxjs observable