Get Started with Angular 4 and Rails 5

This guide will walk you through creating just about the simplest Angular + Rails application possible.

We’re going to create an Angular app, then create a Rails app, then get the two to talk to each other. It should only take a few minutes. Here are the steps.

  1. $ npm install -g @angular/cli

    The Angular app and the Rails app will sit side-by-side in a directory. We’ll call this getting_started although you could call it anything you’d like.

  2. $ mkdir getting_started and $ cd getting_started

    This is the command to initialize the Angular app

  3. $ ng new home-library

    Once this command finishes, cd into home-library and run ng serve.

  4. $ cd home-library then $ ng serve

    You should be able to visit http://localhost:4200

Initialize a Rails app

Now, in a separate terminal, create the Rails app and then create its database. (The –api flag means this will be an API-only Rails app.)

  • $rails new home_library --api -T -d postgresql
  • $cd home_library
  • $rails db:create

Since our “Home Library” app is oriented around books, let’s create a resource called Book.

  • $ rails generate scaffold book name:string
  • $ rails db:migrate

Connect Angular With Rails

Enable CORS so the Angular app can talk to the Rails app

There is a small amount of plumbing work involved to get our Angular and Rails app working. We need to enable CORS (cross-origin resource sharing).

Don’t worry if you’re not familiar with that term. In plain English, we have to tell Rails that it’s okay to let outside apps talk to it.

The first step is to uncomment rack-cors in the Gemfile.

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
# gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Then make config/initializers/cors.rb look like this:
# config/initializers/cors.rb

# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept
# cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      expose:  ['access-token', 'expiry', 'token-type', 'uid', 'client'],
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

And remember to restart the Rails server after you do that.

Get Angular to talk to Rails

We’re almost done. One of the last steps is to add an HTTP request from the Angular app to the Rails app.

  • Modify src/app/app.component.ts to look like this:
// src/app/app.component.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  books;

  constructor(private http: Http) {
    http.get('http://localhost:3000/books.json')
      .subscribe(res => this.books = res.json());
  }
}

This will handle getting the data from the Rails server. Now we need to show it on the page.

<h1>
  {{title}}
</h1>

<ul>
  <li *ngFor="let book of books">{{ book.name }}</li>
</ul>

Now, if you refresh the page at http://localhost:4200

You will need to make a rails seed.rb file to see the books on the page.

0 Comments below

Back

Please log in to leave a comment