如何从类似于 Angular 中的 http 的静态数据创建一个 Observable? [英] How to create an Observable from static data similar to http one in Angular?
本文介绍了如何从类似于 Angular 中的 http 的静态数据创建一个 Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有这种方法的服务:
I am having a service that has this method:
export class TestModelService {
public testModel: TestModel;
constructor( @Inject(Http) public http: Http) {
}
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
//return Observable of JSON.stringify(new TestModel());
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
}
在组件的构造函数中,我是这样订阅的:
in the component's constructor I am subscribing like this:
export class MyComponent {
testModel: TestModel;
testModelService: TestModelService;
constructor(@Inject(TestModelService) testModelService) {
this.testModelService = testModelService;
testService.fetchModel("29f4fddc-155a-4f26-9db6-5a431ecd5d44").subscribe(
data => { this.testModel = FactModel.fromJson(JSON.parse(data)); },
err => console.log(err)
);
}
}
如果对象来自服务器,这会起作用,但我正在尝试创建一个可观察对象,该对象将与给定的 subscribe()
调用一起使用静态字符串(这发生在 testModelService.fetchModel()
不接收 uuid),因此在这两种情况下都可以无缝处理.
This works if an object comes from the server but I am trying to create an observable that will work with the given subscribe()
call for a static string (this happens when testModelService.fetchModel()
does not receive an uuid) so there is seamless handling in both cases.
推荐答案
也许你可以尝试使用 of
方法:
Perhaps you could try to use the of
method of the Observable
class:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
return Observable.of(new TestModel()).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
这篇关于如何从类似于 Angular 中的 http 的静态数据创建一个 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文