聚合物消耗HAL + JSON restful api

时间:2016-02-26 15:56:18

标签: polymer spring-hateoas

我有一个Spring HATEOAS restful api为我的聚合物前端提供数据。

收到的数据如下:

GET /api/tips/news : 

[ {
  "id" : 68,
  "content" : "example tip",
  "score" : 1,
  "creationDate" : 1456257119018,
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:81/api/tip/68"
  }, {
    "rel" : "author",
    "href" : "http://localhost:81/api/user/59"
  }, {
    "rel" : "for",
    "href" : "http://localhost:81/api/class/65"
  }, {
    "rel" : "against",
    "href" : "http://localhost:81/api/class/66"
  }, {
    "rel" : "comments",
    "href" : "http://localhost:81/api/tip/68/comments"
  } ]
} ]

问题是我想从链接中获取author属性,所以我想在第一个请求完成后再做第二个请求。为此,我有一个包含iron-ajax组件的组件,用我的api Key和所有安全性东西做第一个api。

以下是我如何进行第一次api通话:

          <bnstips-api uri="/tip/news" result="{{data}}" auto></bnstips-api>
          <iron-list items="[[data]]" as="item">
            <template>
                <tip-card tip=[[item]]></tip-card>
            </template>
          </iron-list>

这是tip-card组件:

<dom-module id="tip-card">
    <style>
    </style>
    <template>
        <paper-card>
            <div class="card-content">
                [[tip.content]]

                Author:<bnstips-api api-path="[[tip.links.1.href]]" result={{author}} auto></bnstips-api> [[author.name]] [[tip.links.1.href]]
            </div>
            <div class="card-actions">
                <paper-button>Upvote !</paper-button>
            </div>
        </paper-card>
    </template>
    <script>
    Polymer({
        is: "tip-card",
        properties: {
            tip: {
                type: Object,
                value: {}
            }
        }
    });
    </script>
</dom-module>

api-path属性用于提供完整路径而不仅仅是uri,这是背后的逻辑(在bnstips-api中):

    if(this.uri != "" || this.uri != undefined){
        this.url = basePath+this.uri+"?apiKey="+apiKey;
    }
    if(this.apiPath != ""){
        this.url = this.apiPath+"?apiKey="+apiKey;
    }

但我明白了:

bug example

所以提供了链接,但是第二个ajax请求得到了一个错误的uri,因为在控制台中,我可以看到即使属性在这里,我也会收到http://localhost:81/undefined?apiKey.....的请求。

如何避免?

编辑: 我在console.log(this.apiPath)方法中尝试handleRequest(),它显示了良好的值,似乎是一个异步问题(第二个ajax请求在第一个实际结束之前发送,所以第二个ajax请求未定义路径,因为它必须来自第一个。如何在发送第二个之前等待第一个完成?

0 个答案:

没有答案