我有一个具有这种方法的服务:
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());
}
}
}
在组件的构造函数中,我是这样订阅的:
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),因此在这两种情况下都可以无缝处理。
原文由 Michail Michailidis 发布,翻译遵循 CC BY-SA 4.0 许可协议
也许您可以尝试使用
Observable
类的of
方法: