【发布时间】:2017-12-29 15:46:29
【问题描述】:
我的服务类包含以下代码:
Service.ts
//all imports are done
@Injectable()
export class Service{
constructor(private http: Http) { }
getGoogle():Observable<any> {
console.log("Inside service");
return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
}
}
我使用服务的页面组件。
Page.ts
//all imports are done
export class Page1{
constructor(private service: Service, private navCtrl: NavController) { }
async get() {
console.log("inside get method");
const data = await this.service.getGoogle().toPromise();
console.log('The response is' , data);
}
}
我已经得到了所需的结果,但是为了理解 Observables 和 Observer 的概念,我的 Observable 应该有一个 Observer 来订阅。那么为什么不应该代码 const data = await this.service.getGoogle.subscribe().toPromise() 在这里不起作用并显示错误property toPromise() does not exists on type Subscription.
我看到toPromise()的官方资源,我发现它与.just().toPromise()一起使用。然后我发现.just() API声明了
just() 方法将其参数作为 OnNext 通知发出,并且 之后,它会发出一个 OnCompleted 通知。
所以这里用到了订阅的功能,那为什么不用.subscribe()呢?
【问题讨论】:
-
因为
toPromise可以在Observable上调用 - 而不是Subscription- 并且toPromise执行订阅。 -
另外,您问题中的链接引用了 RxJS 4 文档。 RxJS 5 - 这是 Angular 中使用的 - 文档是 here。
标签: promise rxjs observable