Integration of angular 2 tour of heroes with rails 5 api



Hi fellas I know its been a hard journey of angular 2 tour of heroes but now once you are done with tour of heroes you may want it to integrate with Rails 5 api only application and to achieve that first you need a separate rails 5 api only application I have wrote a blog for rails 5 with hero resource just follow that and create a basic rails 5 api app with hero resource.

http://nitanshu.blogspot.in/2016/08/initialization-of-rails-5-api-only.html

In the json you see created_at and updated_at keys it will cause problems on the Angular 2 end since our app is only expecting the id and name attributes. Let’s take care of that right now since we’re already working on the Rails side.
We’ll need to add the active_model_serializers gem to our Gemfile.
gem 'active_model_serializers'
bundle install
mkdir app/serializers
Create a new file called app/serializers/hero_serializer.rb with the following content.
class HeroSerializer < ActiveModel::Serializer
  attributes :id, :name
end
Now you’ll have to add include ActionController::Serialization in your application_controller.rb.
class ApplicationController < ActionController::API
  include ActionController::Serialization
end
If you now hit http://localhost:3000/heros.json you should see only the id and name attributes present (no refresh necessary).

Now restart your rails server with port 3001
rails s -p 3001
you are done with the rails part. now focus on your tour-of-heroes angular 2 application.
either you have toh application or can clone it from my repo.
cd angular2-tour-of-heros/
npm start
now you just need to change few files for some specific reasons

dashboard.component.ts

change the initialize method for dashboard

ngOnInit() {
this.heroService.getHeroes().subscribe(response => this.heroes = response.json());
}

hero.service.ts

change the getHeroes method to this
 
getHeroes() {
  return this.http.get('http://localhost:3001/heros.json')
}
 
main.ts

please comment this line
 
// { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server

now you all set to hit the rails server and get the collection if all goes correct

you'll see this screen.









Comments

Popular posts from this blog

Installing Wowza Streaming Engine on ubuntu

Highcharts with grouped categories

Completely Uninstall and Install Rubymine on ubuntu