【问题标题】:get() is returning arrays as non-arraysget() 将数组作为非数组返回
【发布时间】:2018-06-22 20:13:29
【问题描述】:

我有这个模型:

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"]}
  }
}

【问题讨论】:

    标签: angular falcor


    【解决方案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)
            );
     });
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多