Question

I apologize if this is a real newbie question: I'm coming to AngularJS and restangular as a cold start - I'm porting some older, back-end oriented code into this fancy new world of SPAs and XHRs.

Anyway, this is really simple: I want to load an object from my API. I'm able to do that reasonably easily this way:

App.factory('User', function($cookies, Restangular) {
  if (!$cookies.user_id) {
    return {name: 'Nobody', userId: -1};
  } else {
    return Restangular.one('users', $cookies.user_id).get();
  }
});

App.controller('ApplicationCtrl', function ($scope, User) {
  $scope.user = User;
});

This will (as I understand it) let me inject the current user wherever I need it (and if the cookies aren't right, they end up getting a 404 or 401 on the API call, depending.

The simple problem I'm having now is that when I want to access this user object in my templates, it's not bound to {{user}}, but rather {{user.user}}, as I injected $scope.user with my User object, which was a JSON-created object that restangular fetched (it looked like {"user":{"id":2,"name":"Eric Eslinger","email":"eric.eslinger@gmail.com"}} so if I want to say, "hello username" I have to say "hello, {{user.user.name}}". Which is unsatisfying.

Any advice about what I'm missing in setting up my object heirarchy is welcome; I have a feeling I'm just missing something simple but also important that I'm going to need to worry about later.

Was it helpful?

Solution

To answer my own question, this isn't really a restangular thing, it's a general angular thing (ngResource behaves the same way) and is a bit of orthoganality to how EmberJS works. In EmberJS, (or at least the version of Ember-Data that I was using), JSON api responses are expected to have a root element, which Ember-Data kind of disregards (or uses to type the result objects). $resource and restangular attend to the root elements. So you can alter your api to just return {"id:2" ... instead of {"user":{"id":2 ... or you can do a transformResponse on the result. Your call.

Since I'm writing both the API and the front end, and there's nobody else using this API right now (once it stabilizes, that will change), I just went and changed how the API output JSON. The backend uses active_model_serializers, so I just put a , root: false in a few choice locations for now. Easy enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top