如何从类似于 Angular 中的 http 的静态数据创建一个 Observable?

2024-04-11

我有一个具有此方法的服务:

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),因此在这两种情况下都有无缝处理。


也许你可以尝试使用of https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/of.md的方法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());
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从类似于 Angular 中的 http 的静态数据创建一个 Observable? 的相关文章

随机推荐