get()将数组作为非数组返回

时间:2018-01-13 16:39:44

标签: angular falcor

我有这个型号:

let model = new falcor.Model({
    cache: {
        hStudents: {
            801: {
                FirstName: 'Samuel',
                LastName: 'Forbes'
                },
            802: {
                FirstName: 'Chad',
                LastName: 'Pennington'
                }
            },
        lStudents: [
            $ref(['hStudents', 801]),
            $ref(['hStudents', 802])
            ]
        }
    });

当我执行下面的代码时,尽管lStudents是模型中的一个数组,但我还是找回了一个不是数组的对象。出于这个原因,我不能使用Angular的* ngFor迭代对象。为什么我不会回到阵列?

return this.model.get("lStudents[0..1]['FirstName','LastName']")
    .progressively()
    .subscribe( (h) => {
        console.log(JSON.stringify(h));
        });

打印:

{"json":{
  "lStudents":{
    "0":{"$__path":["hStudents","801"],"FirstName":"Samuel","LastName":"Forbes"},
    "1":{"$__path":["hStudents","802"],"FirstName":"Chad","LastName":"Pennington"},"$__path":["lStudents"]}
  }
}

1 个答案:

答案 0 :(得分:1)

Falcor将数组视为具有等于数组项索引的键的对象。请参阅文档示例here

原因是因为lStudents列表是分页的,所以它必须处理"lStudents[10..19]['FirstName','LastName']"之类的查询。如果结果是数组而不是对象,例如{ "json": "lStudents": [ <items 10 - 19> ] },它会与要求学生0 - 9(或任何其他学生列表查询)的类似查询冲突。

要处理表示列表的对象,请将jsonGraph响应转换为数组。像lodash或ramda这样的实用程序库可能会派上用场。

this.model.get("lStudents[0..1]['FirstName','LastName']")
    .progressively()
    .subscribe((jsonEnvelope) => {
       /* using Ramda and transforming 
        * { "FirstName":"Samuel","LastName":"Forbes" }
        * to { "FirstName":"Samuel","LastName":"Forbes", "index": "0" }
        */
        console.log(
          R.compose(
            R.map(([studentIdx, student]) => ({
              ...student,
              index: studentIdx
            })),
            R.toPairs
          )(jsonEnvelope.json.lStudents);
        );
        /* using Ramda and ignoring index
         */
        console.log(
          R.values(jsonEnvelope.json.lStudents)
        );
 });