这里的“数据”在下面的代码中有什么用?为什么在getReview()中使用promise?

时间:2017-05-10 07:29:01

标签: angular ionic2

代码评论中也提供了一些问题。

代码:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Reviews {

  data: any;

  constructor(public http: Http) {
    this.data = null;
  }

  getReviews(){

    if (this.data) {
      return Promise.resolve(this.data);//what is the use of this promise here?
    }

    return new Promise(resolve => {

      this.http.get('http://localhost:8080/api/reviews')
        .map(res => res.json())        //do we use .map operator in observables only? also the subscribe function? do we not use here .then?
        .subscribe(data => {         
          this.data = data;
          resolve(this.data);
        });
    });

  }

  createReview(review){

    let headers = new Headers(); // what is the use of headers here?When do we use these headers?
    headers.append('Content-Type', 'application/json');

    this.http.post('http://localhost:8080/api/reviews', JSON.stringify(review), {headers: headers})
      .subscribe(res => {
        console.log(res.json());
      });

  }

我在那里读到this tutorial我找到了这段代码。请帮我解决。这是代码中使用的Service类。我们什么时候可以使用Observables和promises?

对于参考和理解,我已阅读帖子的堆栈answers

1 个答案:

答案 0 :(得分:1)

此处所做的是更喜欢Promise而不是Observable的人,但却以一种好奇的方式实施了。{p>}例如,使用toPromise运算符和async/await功能,您可以像{{}}那样获得更易理解的getReviews()代码:

async getReviews(): Promise<any> {
    if (!this.data) {
        this.data = await this.http.get('http://localhost:8080/api/reviews')
            .map(res => res.json())
            .toPromise()

    }
    return this.data;
}

这样做的好处是,如果在getReviews()方法上有多个调用,则在返回数据之前,API仅被调用一次。用你的&#39;实现,API被多次调用很可能,以获得相同的数据集

在您的代码中回答您的问题:

  • Promise.resolve()的使用是以promise表单的形式返回缓存的数据结果。这样,方法的返回类型始终为Promise<any>,因此您始终可以使用this.getReviews().then(...)。向方法添加严格的返回类型将使这一点变得清晰。在我的例子中,我已经翻开支票,这意味着它将始终返回相同的承诺。
  • 地图运算符是Observable(rxjs)运算符,用于在数据发送给订阅者之前修改数据。不要与数组上的默认map运算符混淆,大致相同。
  • 请求服务器需要时使用标头。在这种情况下,它告诉服务器请求的有效负载包含JSON数据