LoginSignup
14
16

More than 5 years have passed since last update.

angular4とrails5をスッと使ってみる

Last updated at Posted at 2017-05-05

Rails5で簡単なAPIを作成し、Angular4で表示します。

今はAngularJSでアプリ開発をしていますが、
Angularへの移行を夢見てちょっと試してみた時のメモです。

Versions

バージョン
Angular 4.1.0
ruby 2.4.0
rails 5.1.0

Angular 4

詳しくはhttps://Angular.io/ を参照。

AngularCLIインストール.
npm install -g @Angular/cli
test用ディレクトリ作成.
mkdir testApp
cd testApp/
angulatアプリ作成.
ng new test-web
cd test-web
実行.
ng serve

http://localhost:4200 を叩く

Screen Shot 2017-05-06 at 0.48.32.png

実質コマンド2つでAngularは動く!

rails5でAPI作成

rails5.1のwebpackオプションは使いませんm(_ _)m

railsアプリの作成.
rails new test_api --api -T -d mysql
cd test_api
rails db:create
comment.rb
rails generate scaffold comment name:string
rails db:migrate
db/seeds.rb
Comment.create!([
  { name: "I'm Kanadai." },
  { name: 'カナダイです' }
])
seed投入.
rails db:seed
実行.
rails server

API完成

http://localhost:3000/comments.json
Screen Shot 2017-05-05 at 23.39.19.png

AngularからRailsのAPIを叩く

Angular側

component.tsに// 追加の箇所を追記

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!';
  comments; //追加

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

component.htmlにも追加

src/app/app.component.html
<h1>
  {{title}}
</h1>

<!--追加-->
<div *ngFor="let comment of comments">{{ comment.name }}</div>

http://localhost:4200 を叩いてみる。。

Screen Shot 2017-05-06 at 0.16.52.png
はいダメー。cors.rbを追加します。Rails側を参照↓

Rails側

Gemfileのgem rack-corsのコメントを外す

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

bundle install

cors.rbのコメントを外す。

config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

productionではちゃんと設定しよう。。
https://github.com/cyu/rack-cors

Railsサーバーを再起動

もう一度http://localhost:4200 を叩く
Screen Shot 2017-05-06 at 0.40.52.png

OK!seedの内容が表示されました!


いやーAngularCLI本当に便利ですね。ほとんど何もしなくてもサラッと動く。α版の時はめちゃめんどくさかった気がするんですけど、実質コマンド2発で動いちゃう。
でも中身を全然見てませんね〜笑

次はGoogle認証を試してみます〜

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16