Persistence with Ember Data and Ember App Kit
Published on Apr 29, 2014
Connecting to a separate server can be difficult, especially on localhost. Here's how to do it with Ember Data and Ember App Kit.
You can imagine that we are using whatever you're using on the server side, whether that is Ruby, Python, Elixir, Node, Java, PHP or Visual Basic, whatever, it doesn't matter because we'll be showing none of those in this screencast series. However, even though we are only stepping slightly outside the bounds of our application, being able to access JSON API greatly expands what we are able to do.
For the purposes of our podcast today, what we are gaining is the ability to process data. Right now, when you make an edit, and then reload the page, your edit is gone. We want to fix that. Here is an example of the JSON that we'll be using. In this case, it's the post resource accessed via a get call. It's the same type of data that we've been using so far, the same format, but now it's coming from the server. In order to get this API working with our application, we'll need to change just a few things.
The first is to change the adapter. Most of you will want the REST adapter, but if you happen to be using active model serializers, then you'll use the ActiveModel adapter.
Now Ember knows how to expect your JSON to be formatted. If your API is not very consistent, go ahead and check out episode 1 to see how to make a per-model adapter. We'll also need to make sure that Ember data knows the namespace for our API. We'll use the namespace option and just give it a string. In this case, our namespace is api/v1.
Next we need to setup a proxy server in order to get around Cross Origin Resource Sharing woes, or CORS. CORS is built to protect your website but it is also annoying when you are working in a dead environment. The proxy server is a weird work-around, but with Ember App Kit it's not that hard to pull off. All you have to do to set it up is to put these 3 lines in your package.json. As you can see they'll be replacing the stub method that was there before, and we'll have to put quotes around it, and then of course we'll have to change it that it matches our server's configuration. Then you'll have to restart your Grunt server so that you'll have the new proxies.
Now our app is loading from the server, but still if we edit something like, say, correcting this spelling error, then if we reload it still won't save. That's because we never tell it to! Fortunately, Ember Data makes this very easy. All we have to do is call this.get('model') and then save that model, and that will happen when we hit the done editing button. Now we can edit it again, we can correct the spelling again, and when we reload we'll see that it has saved.
And that's all there is to it! Of course once you have relationships between your models stuff gets a bit more complicated, but that's for another episode. Happy coding!