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

新手上路,请多包涵

我有一个具有这种方法的服务:

 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 许可协议

阅读 613
2 个回答

也许您可以尝试使用 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());
  }
}

原文由 Thierry Templier 发布,翻译遵循 CC BY-SA 3.0 许可协议

截至 2021 年 5 月,从值中获取 Observable 的新方法是:

输入:

 import "rxjs/add/observable/of"
import { Observable } from "rxjs/Observable"

并使用,像这样::

 Observable.of(your_value)

原文由 danilo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题