我是 Aurelia 新手,已经阅读了 PluralSight 和 Egghead.io 上的教程,但仍然无法解决我的问题。
我有一个 json 文件,我们将其命名为 bob.json。里面有一系列关于鲍勃的元素。每个对象都有一个 id。我想使用箭头表示法通过 id 获取集合中的对象。这是我到目前为止所做的事情。
bob.json
[
{
"id": 1,
"name": "eyes",
"position": "head",
"color": "blue"
},
{
"id": 2,
"name": "nose",
"position": "head",
"shape": "triangle"
},
{
"id": 3,
"name": "mouth",
"position": "head",
"chapped": true
},
[more body data here]
]
person.html
<template>
<ul repeat.for="bodypart of bodyparts">
<li>
<a id="${bodypart.id}" href="javascript:void(0);" click.trigger="displayPart($event)">${bodypart.name}</a>
</li>
</ul>
</template>
person.js
import {inject} from "aurelia-framework";
import {BodyData} from "bodyData";
@inject(BodyData)
export class(bodyData) {
constructor(bodyData){
this.bodyData = bodyData;
}
activate(){
return this.bodyData.getAll().then(bodyparts => this.bodyparts = bodyparts)
}
displayPart(e){
this.bodyData.getBodyPart(e.target.id)...
}
}
bodyData.js
import {inject} from "aurelia-framework";
import {httpClient} from "aurelia-http-client";
let baseUrl = "bob.json";
@inject(httpClient)
export class BodyData {
constructor(httpClient){
this.http = httpClient;
}
getAll(){
return this.http.get(baseUrl).then(response => { return response.content });
}
getBodyPart(id){
return this.http.get(baseUrl).then(response => {
return response.content.filter(n => n.id == id);
});
}
}
省略号部分是我不知道为箭头函数添加什么内容的地方。我的问题是,有人可以帮助我了解需要在这些区域放置什么才能返回与特定 id 匹配的对象,以及解释如何使用带有 json 数据的箭头表示法的最佳资源在哪里。
更新:
所以我找到了一个很好的解释:
https://googlechrome.github.io/samples/arrows-es6/
据我所知,它在某种程度上类似于 SQL 语句。
在 bodyData.js 中我使用了这个语句:
getBodyPart(id) {
return this.http.get(baseUrl).then(response => {
return response.content.filter(n => n.id == id);
});
}
现在,我的理解是过滤返回的内容,其中对象 id 等于传入的 id。 SQL 的读取方式如下:
SELECT [object]
FROM [json file]
WHERE [object].id = id
如果这是正确的,那么我想我得到了那部分。现在真正让我困惑的部分是 person.js 文件中的 displayPart(e) 函数。如何查看此数据以查看它是否返回正确的值?非常感谢任何帮助。
最佳答案
Eureka !我做到了!好吧,让我冷静下来,因为你们很多人可能认为这很小,但对我来说却很重要。这是最后的作品。在我上面完成更新之后,您必须在 promise THEN 语句内执行所有后续步骤。
因此,将我的示例中 person.js 类中的 displayPart(e) 代码替换为以下内容:
displayPart(e){
this.bodyData.getBodyPart(e.target.id).then(bp => {
this.bp = bp;
// Whatever code/functionality you plan to do with the body part next by using this.bp to access the collection.
});
}
这将返回与我发送的 id 匹配的对象集合。哇!问题解决了。希望有一天这会对某人有所帮助。
关于javascript - Aurelia 上带有 json 文件的箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948098/