0

I have an AngularJS app that I am converting to use js-data. If I have a REST interface that returns a JSON object in this format

{
  data: {
    id: 1,
    name: Test,
    dept: 2
  },
  related: {
    DeptList: [
      { Id: 1, Name: Dept1 },
      { Id: 2, Name: Dept2 },
      { Id: 3, Name: Dept3 }
    ]
  }
}

how do I go about extracting related.DeptList and injecting it into js-data? I have a deserialize function that can return the data object, but can't see how to extract the related data.

1 Answers1

0

In JSData 2.x, one approach is to iterate over the relationList field of the Resource passed to deserialize, and move relations from your related field over into their expected position.

Here is a plunker that demonstrates: https://plnkr.co/edit/suesxw?p=preview

The code in that plunker is pretty general, but there probably some missed edge cases and improvements that can be made to better fit your use case.

Here is a slightly different example based on the new JSData v3 beta: https://plnkr.co/edit/IZJa6jP4cxySlbyRFYF3

jdobry
  • 1,041
  • 6
  • 17
  • Thanks @jdobry, that's perfect for a hasMany relationship. I wasn't clear enough, sorry. The record in question is a user, so the relationship is a hasOne. I thought I'd be able to reference DS from inside deserialize, so I can just say DS.inject(relatedData) but I don't know how to reference a related resource from the resource itself. – Ashley Johnson May 08 '16 at 20:49
  • This is what I was hoping to achieve `DS.inject(def.localField, relatedData)` – Ashley Johnson May 08 '16 at 20:56
  • No, you're right ... your solution works for hasOne relationships too. Perfect, thank you very much. – Ashley Johnson May 09 '16 at 00:03