How to insert controllers in Ionic


#1

Hi Guys, i’m starting with ionic v3 and i’m trying to use rack cors gem with Ionic 3 but i dont know how to do this.
I have a Rails 5 API working with this gem but only in ionic v1 so i’d like to implement the ionic v3 in front-end. i found a nice tutorial to do that, but is working in ionic v1, so i dont know how to do the same using ionic v3.
This is the tutorial: https://www.youtube.com/watch?v=M3MnOZmGu3k&t
I just have one problem, how to insert controllers in ionic v3? anybody know how to do? because in another version of ionic we had a file called “app.js” but in ionic v3 we don’t have… help me please, thanks!


#2

So it sounds to me like you’d want to create a provider that would interact with your API, and then on each page that you need to get data from your API you just inject and use the provider.

Providers (at least normally) go under src/providers, and would like something like this:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MyApi {
  constructor(public http: Http) {
  }

  public getData() {
    return this.http.get('myurl.com/api/data');
  }
}

This is obviously a larger concept suggestion, but in broad terms this is the path to go.


#3

thanks for reply SugmundFroyd!
do you know if this providers can be created using some comand line like creating pages? or i need to create manually?
thanks my dear friend!


#4

You can indeed:

ionic g provider MyApi

#5

thank you man! i’ll try with your tips.
I have this function where i get data from my Rails 5 API and everything is working in my test using ionic v1:

(function(){
	var app = angular.module('userController', []);
	app.controller('UserController',
	function($scope, $http) {
		var url = 'http://localhost:3000/api/people';
		$http.get(url)
		.success(function(people) {
			$scope.people = people;
		})
		.error(function(data) {
			console.log('Ocorreu um erro no lado do Server.');
		});
		}
	);	
})();

So following your steps i i’ll create one provider right? and after to create this provider i need to insert my function or i can try using other way?
Talking about my ionic view, i just have a list to show data there, only to start my studies, but after do that i’ll try to send querys and try to authenticate using user and password, this is my view:

 <ion-header>
  <ion-navbar>
    <ion-title>Usuários</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <button ion-item *ngFor="let usuario of usuarios" (click)="itemSelected(item)">
      {{ usuario }}
    </button>
  </ion-list>
</ion-content>

Thanks again and sorry about my questions man… i’m learning…