我有一个具有此方法的服务:
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) ); } }
如果一个对象来自服务器,这是有效的.但是我试图创建一个observable,它将使用给定的现有subscribe()调用静态字符串(当testModelService.fetchModel()没有给出一个uuid时会发生这种情况)因此在这两种情况下都有无缝处理.这可能吗?
也许您可以尝试使用Observable类的
of
方法:
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()); } }