尝试使用Angular4和Rails5

使用Rails5创建一个简单的API,并在Angular4中进行展示。

我目前正在使用AngularJS进行应用开发,但以下是我尝试迁移到Angular时的备忘录。

版本

バージョンAngular4.1.0ruby2.4.0rails5.1.0

Angular 4:角度4

请查看https://Angular.io/以获取更详细的信息。

npm install -g @Angular/cli
mkdir testApp
cd testApp/
ng new test-web
cd test-web
ng serve

请求 http://localhost:4200

Screen Shot 2017-05-06 at 0.48.32.png

使用仅仅两个实质命令即可使Angular运行!

使用Rails 5创建API

我不使用Rails 5.1的webpack选项。

rails new test_api --api -T -d mysql
cd test_api
rails db:create
rails generate scaffold comment name:string
rails db:migrate
Comment.create!([
  { name: "I'm Kanadai." },
  { name: 'カナダイです' }
])
rails db:seed
rails server

API已经完成

Screen Shot 2017-05-05 at 23.39.19.png

使用Angular调用Rails的API

Angular的一侧

在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中添加

<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

让我们专注于Rails。

删除Gemfile中rack-cors这个gem的注释。

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

安装软件包

解除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

在生产环境中,需要妥善进行设置。请参考以下链接:https://github.com/cyu/rack-cors

重新启动Rails服务器。

Screen Shot 2017-05-06 at 0.40.52.png

好的!种子的内容已经显示出来了!


哎呀,Angular CLI真的很方便啊。幾乎不需要做任何事情就能輕輕鬆鬆運行。我覺得在α版本時它真的很煩人,但實際上只需要兩個指令就可以運行。但我根本沒有看過它的內部結構呢~哈哈

接下来我会试试Google认证~

bannerAds