如何创build一个类似于Angular 2中的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) ); } } 

这工作如果一个对象来自服务器..但我想创build一个观察,将与现有的subscribe()调用静态string(这发生在testModelService.fetchModel()没有给一个uuid ),所以在这两种情况下都可以无缝处理。 这可能吗?

也许你可以尝试使用Obserableof方法:

 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()); } } 

事情似乎已经改变了Angular 2.0.0

 import { Observable } from 'rxjs/Observable'; import { Subscriber } from 'rxjs/Subscriber'; // ... public fetchModel(uuid: string = undefined): Observable<string> { if(!uuid) { return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o)); } else { return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) .map(res => res.text()); } } 

.next()函数将在您的订阅服务器上被调用。

这是你如何创build一个简单的静态数据观察。

 let observable=Observable.create(observer => { setTimeout(() => { let users = [{username:"balwant.padwal",city:"pune"}, {username:"test",city:"mumbai"}] observer.next(users); // This method same as resolve() method from Angular 1 console.log("am done"); observer.complete();//to show we are done with our processing // observer.error(new Error("error message")); }, 2000); }) to subscribe to it is very easy observable.subscripe((data)=>{ console.log(data); // users array display }); 

我希望这个答案是有帮助的。 我们可以使用HTTP调用来代替静态数据。