How to access HAL _links within _embedded resources with JavaScript / AngularJS

910 views Asked by At

I appreciate there are several libraries to work with HATEOAS linkrels in HAL format, but I would love to learn more about accessing _embedded resource(s) and its _links in the most basic - or I guess I should say naive - way.

As an example, I have the following "usersResource" ($http) Spring HATEOAS output:

{  
   "_embedded":{  
      "userList":[  
         {  
            "username":"admin",
            "roles":[  
               "ADMIN"
            ],
            "_links":{  
               "self":{  
                  "href":"http://localhost:8081/users/admin"
               },
               "password":{  
                  "href":"http://localhost:8081/users/admin/password"
               },
               "delete":{  
                  "href":"http://localhost:8081/users/admin"
               }
            }
         }
      ]
   },

   "_links":{  
      "self":{  
         "href":"http://localhost:8081/users"
      },
      "create":{  
         "href":"http://localhost:8081/users"
      }
   }
}

If I run something simple like usersResource.$hasEmbedded("userList") or usersResource.$hasLink("create"), I get true with no problems.

If I then try something more adventurous like usersResource.$request().$get("userList") I get a resource object back but I'm struggling to use that object in any meaningful way.

For instance, if I wanted to check if the "password" linkrel exists for my admin user, is there any way I could use the returned resource object and call $hasLink on it?

Thanks for comments!

1

There are 1 answers

0
PTrek On BEST ANSWER

So anyways, I only later noticed that the object returned by the usersResource.$request().$get("userList") call is an array. So then it's just a matter of looping through the array to get to the $hasLink etc. methods. In my case, I just needed to get to the first [index 0] object. This did the trick:

usersResource.$request().$get("userList")
            .then(function (users) {

                vm.users = users;

                console.log("$hasLink 'delete'");
                console.log(users[0].$hasLink("delete")); //return true

                }
            );