typescript – 如何从Angular中类似于http的静态数据创建一个Obs
发布时间:2020-12-17 07:54:56 所属栏目:安全 来源:网络整理
导读:我有一个具有此方法的服务: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observablestring { if(!uuid) { //return Observable of JS
我有一个具有此方法的服务:
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()); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- Scala TraversableOnce和toSet
- scala – 为什么我在一个环境中而不是另一个环境
- twitter-bootstrap-3 – Jasny Bootstrap在提交后
- scala – Play Framework 2.3和javascript webso
- angular – 测试未捕获错误:macroTask’setInte
- 你在OSX上保留自己的脚本在哪里?
- Shell简介:1分钟理解什么是Shell 脚本语言 解释
- bash – rc.local文件无法使用raspberry pi
- 什么是AngularJS中的$on()
- Angular2和webpack – i18n插件与ng2-translate
热点阅读