Titten Pumpen, Teen Sex Mit Tieren, Sex In Ludwigshafen, Sexmovie Com, Extrem Vollbusige Harlow Harrison Laesst Bbc Eindringen Ihre Hungrig Muschi, Www Mature Sex Tube, Aerztin Fickt Patient, Junge Suesse Mancy Erleben Ihre Ersten Erotischen Massage, Swinger Ruhrgebiet, Zwei Stuermischen Lesben Lecken Und Fingersatz Ficken Leidenschaftlich, Erotische Sex, Sai Tai Die Haremswaechterin Full Movie German, Pissschlampe, Asiateen, Bruder Und Schwester Sex Tube, Teen Meuse, Lana Giselle Pornos, Horny Sister, Brazzers Porb, Kostenfreie Porno, Nackt Pervers, Redtube C0m, Porno Im Kuhstall, Die Beliebtesten Videos Von Tag Freiluft Ficken, Lucycat Dreier, Armenian Sex Tube, Maedchen Solo, Tsunade Porno, Sex Auf Der Strase, Conny Dachs Fickt Blonde Stiefel Braut Anal, Lucie Wild Porn, Xxx Ok, Momoldcom, Phoenix Maries, Lingerie Tube Sex, Spanking Po, Lexy Roxx Porno Opa, Riley Evans Pornos Sexfilme Kostenlos Frauporno, Frauen Beim Sex Kostenlos, Extrem Titten, Porno Nylon, Porno Hefte, Deutsche Junge Maus Anni Angel Fickt Mit Alten Sack Direkt Am Strand Beim Usertreffen, Escort Friedrichshain, Carter Porn, Schnuggie91 Model Page, Xvideosm, Alte Nutten Porno, Omas Nacktfotos, Gruppensex Privat, Iwank Videos, Sex Lll, Versuch Nicht Zu Kommen, Geile Mollige Weiber, Harry Potter Xxx Parody, Pornos Behaart, Rachel Starr Brazzers, Skinny Titten, Sex Im Autohaus, Pilladas, Swinger Freunde Aus Germany Ficken Geil Querbeet, Steife Nippel Porno, Maenner Am Fkk Strand, Spy Cam Records Office Sex, Ficken An Der Bar, Naked Old Man, Www Porno Xxx Com, Junge Julia Aus Bremen Laesst Sich Vor Der Kamera Ficken, Bdsm Gang Bang, Helikopter Sexstellung, Nackte Tattoo Girls, Maedchen Schlucken, Spritz Porn, Lara Bergmann Porn, Grosse Geile Schamlippen, Bikini Bondage, Teacher Stockings, Veugeln Porno, Mann Fickt Schaf, Die Beliebtesten Videos Von Tag Schwestern Ficken, Muschi Gepierct, Hentai Schwanger, Hiden Cam Porn, Public Agent Porn, Moslim Porn, Schwarzer Fickt Blondine, Pornos Gratis Gucken, Nackte Lesben, Titten Besamen, X Videosde, Angesprochen Abgeschleppt Durchgefickt Vollgespritzt, Scarlett Johansson Hot Scene, Harley Jade Pornos Sexfilme Kostenlos Frauporno, Ungarische Bruenette Mit Kurven Deborah Diamond Wird Mit Sperma Gefuettert Nachdem Sie Alle Loecher, Xnxx Boys, Gay Bareback, Cortney Kane, De Xhamstercom, Geilsau Gina Laesst Es Sich Auf Einem Heuballen Ordentlich Besorgen, Schwanger Nackt Sex, Erstaunlich Kurvige Schwarze Lady April Aniston Wird Geschmiert Und Hart Gefickt, Mini Pornos, Mara Martinez Beim Renovieren Ins Arschloch Gefickt, Die Geilsten Fotzen, Abspritzen Deutsch, Backroom Casting Couch Porn, Dad And Daughter Porn, Black Stepdad Porn, Anime Big Boobs, Sex Milfs, Sexy Bruenette Dirne Jessica Hot Gefaellt Ihre Eifrig Kerl Auf Pov Cam, Karina Fotze, Erotikshop Bonn, Sensual Jane Milf, Porno Hardcore Vergewaltigung, Gangbang Trailer, Wwwbumsen, Laengste Videos Nach Tag Blowjob Porn, Blonde Schlampe Nina Elle Bekommt Ihr Schlitz Leckte Und Knallte, Bordell In Ravensburg, Extremes Fisting In Votze Arschloch, Die Beliebtesten Videos Von Tag Milf Will Sex, Big Tits Porno, Nackte Frauen Mit Dicken Arsch, Walnuesse In Honig, Schwabelige Hausfrau Wird Im Badezimmer Gefickt, Die Beliebtesten Videos Von Tag Club Seventeen, Wehrlos Porno, You Prn, Karneval Sex Tube, Nackte Frauen Voyeur, Suche Nach Tag Bumsen Mit Teenie, Outdoor Sex Porn, Wwwpornoro, Leah Livingston, Perfect Girls 10000, Ficken Kaufen, Grosse Tetten, Mutter Und Tochter Ficken Auf Dem Balkon Rum, Ber 70 Und Dennoch Rattig, Porno Anschauen Kostenlos, Lebenporno, Xnnncom, Doppelpenetration Porno, Teen Luder Mit Zwei Schwaenzen, Huren Olpe, Michaela Schaefer Porno, Arschleucher Lecken, Sexfilme Hd Kostenlos, Freundin Pussy, Einfachporno Lisa Ann, Sexy Deutsch, Free Porn Orgie, Deutsche Omapornos, Vidios Porno Gratis, Bruenette Mit Schoenen Zimmern Die Mit Viel Koerper Crystal Rae Knallte In Pov, Magma Film German Masquerade Swingers Party, Cfnm Handjob Videos, Medieval Hentai, Sex In Baden Baden, Sex Clips, Massage Keuln Happy End, Junge Maedels Porno, Youporn Alexa, Free Teresa Orlowski, 18 Jaehrige Pornodarstellerin, Deutsche Wichsanleitung Von Dominanter Lady German Femdom Cum Manual Bdsm, Pornofilme Inzest, Spanking Porno, Alte Schlampen Ficken, Geile Swinger Party, Teen Muschi Fick, Er Sucht Ihn Berlin Sex, Free Hot Porno, Porn Pants, Fotzen Des Tages, Reife Schlabber Fotze Wird Von Bodo Gefickt, Windelstrafen, Teen Vision Kleine Seue Erwischt Und Bestraft 1 1 1, Mom Help Son Porn, Schoene Mollige Frauen, Die Beliebtesten Videos Von Tag Deutsche Fickfilme, Reife Damen 50, Fussfetisch Videos, Nadya Nabakova Xxx, Slim Milf Enjoys Piledriver 69 And A Good Fuck Until He Busts A Nut In Her Mouthexcl, Alte Lesben Pissen, Leere Schlauchtitten, Gewalt Sex Videos, 3d Porn Download, Atemberaubenden Ebenholz Schlampen Bewegt Ihren Grossen Arsch Sitzen Auf Weissen Schwanz, Faye Regan, Reifeswinger, Top Bewertete Videos Von Tag Deutscher Inzest Porno, 90 Porn, Suche Nach Tag Reife Ficksau, Schwiegermutter Gefickt, Grosse Schwaenze, Vaginal Dehnung, Spontaner Outdoor Fick Am See Mit Blondem Luder, Sex Ladies De, Brutaler Sex Schlampe Wird Im Rollenspiel Vergewaltigt, Nuru Massage Saarbruecken, Young Orgasm Sex Tube, Dacota Sky, Ferrera Gomez Sex Tube, Duerre Omas, Frivol Porno, Geschwaengert Porn, Geile Studentin, Porn Video Free, Pisse Trinken Sex Tube, Ronny Sex, Swingerclub Giessen, Nackte Maedchen In Der Oeffentlichkeit, Dicke Negerin Ficken, Stella Cox Deepthroat, Viel Sperma In Der Muschi, Sybian Orgasmus, Sexy Brunette Girl Toys And Fingers Her Pussy, Suche Nach Tag Mareen Deluxe, Flatratepuff, Hard Porn Sex, Hot Girls Ficken, Sex Tube 88, Teen Hot Pants, Frauen Ficken Mit Dildo, Heute Porn Swinger, Ehrfuerchtige Brasilianische Stripperin Gina Valentina Arbeitet Auf Starke Schwarze Schwaenze, Crystal Crown Porn, Johnny Sins Kissa Sins, Fake Agent Pornos, Schlanke 18 Jahre Junge Nachbarin Beim Privaten Ficken Aufgenommen, Kelly Shibari Ist Bis Zu Einige Schwanz Saugen, Blondine Im Bikini Posen Und Bekommt Ihr Arschloch Und Muschi Lecken, Lucy Li Porn, Porno Lack Und Leder, Ficken Mit Der Schwiegermutter, Tennie Film, Geile Bilder Zum Wichsen, Krankenschwester Xxx, Amateur Bruenette Victoria Rose Hat Im Freien Flotter Dreier, Free Long Porno, Lucy Cat 94, Sm Femdom, Www Black Sex, Hypnose Hentai, Stepmomlessons, Schulmaedchen Werden Gefickt, Beim Nachsitzten Verfuehrt Und Gefickt, Albania Sex Tube, Schlaege Auf Po, Anal Casting Teen, Tony De Sergio, Conny Dachs Fickt Eine Kleinwuechsige, Bad Laasphe Porno, Sex Tube Wixanweisung, Fotze Lecken Und Fingern, Teen Whore Sister Fucks Brother, Ostern Xxx, Rothaarige Jung Schlampe Bumst Im Retro Porno Deutsch, Dicke Weiber Voegeln, Mutter Mit Gewalt Gefickt, Schwanger Gefickt, Whatsapp Nummern Sex, Desi Sexcom, Privatamateure Top Videos Juli 2013, Upskirt Japan, Monsterfick, German Creampie Bitch Outdoor Fuck, Mydirtyhobby German Amateur Chubby Babe Proposes That Her Boyfriends Best Friends Fucks Her Outsid, Cuckold Sperma, Deutsche Mama Beim Masturbieren Im Bad Ueberrascht, Greusster Kitzler Der Welt, Free Piss Sex, Reife Frau Mastubiert, Huebsche Teens Nackt, Heute Pprno, Hd Filme Porn, Lara Kumkitten, Deutsche Paare Beim Ficken, Mann Mit 2 Penen, Party Slut Janine Loves Her Toy Real Dicks Even Moreexcl, Www Ledis De Hildesheim, Milf Handjob Videos, Flatrate Bordell Nuernberg, Mollige Nackte Teens, Anal Fist Extreme, Maedchenfotze, Behinderten Sex Porno, Geile Koreanerin, Ich Hol Mir Ein Runter, Junge Wixer, Mely Deluxe, Heisses Flittchen Von Den Kerlen Hart In Den Anus Gebumst, Uniform Sex, Aj Applegate Ist Eine Sexy Dynamischen Lesbische Maedchen Und Sie Liebt Geben Oral Sex, Big Tits Milf, Die Beliebtesten Videos Von Tag Privat Ficken, Blowjob In Der Kueche, German Amateur Junge Berliner Nutte Mit Livecam Am Pc Beim Ficken Einfach Aufgenommen Ohne Das Sie, Gratis Muschifilme, Brandi Edwards Anal, Lustig Xxx, Free Sex Sport, Junge Amateur Schlampe Wird Bei Sexparty Von Vielen Maennern Besamt, Italien Inzest Porn, Izzy Delphine, Porno Schere, Sextreffen Euskirchen, Tanga Sex Tube, Sex In Norden, Friends Wanking, I Feel Myselfcom, 80 Er Porn, Porn Cam Deutsch, Freeyourporn, Transe Mannheim, Gurke Porn, Blonde Nackte, Entfuehrungs Porno, Sportliche Frauen Nackt, Dugs, Www Xnxxcom, Sexshop Heilbronn, Forbondage School Teen Ariana Love Try European Bdsm Fetishes, Sexy Jeans Teen, Geile Rasierte, Domina Porno Gratis, Votzen Und Titten, Xhamsts, Nackte Frauen Beim Duschen, Big Tits Casting, Amazing Cumshot, Oma Und Opa Sind Noch Geil, Epxv1369, Milf Dacada Fickt Mit Riesen Schwanz Bimbo, Deutsche Schuelerin Braucht Geld Und Bewirbt Ich Zum Pornocasting, Pussy Tattoo Porn, German Milf Fucks Outdoors, Two Filthy Sluts Get Trained During A Hard Anal Session With Ass To Mouth, Sex Auf Der Farm, Kenzie Kellie Ist Sehr Zierlich Kann Aber Mit Einem Riesigen Schwanz Umgehen, 3d Monster Sex, Maedchen Fickt Opa, Anal Sex Hd, Drei Sklavenrosetten Von Lady Susan Erzogen, Maedchensexde, Tantra Recklinghausen, Bordell Bingen, Nackte Matures, Sadomaso Free Video, Scheussliche Orgie Mit Drei Japanischen Schlampen Im Whirlpool Im Freien, Wild Cam Porn, Frau In Leggins Gefickt, Full Hd Pron Video, Kostenlos Lesbenvideo, Milfs And Cougars, Lespen Masage, Tantric Sex Video, Bdsm Kostenlos, Pornokino In Duisburg, Porno Mia, India Summer Blowjob, Deutsche Pornos Online, Free Porno Casting, Fellationieren, Dikke Oma, Sex At Home Tube, Allison Moore Hat Eine Leidenschaftliche Erotische Massage, Extrem Sex Video, Hidden Cam Spy Porn, Kenzie Kai, Erotik Selfies, Junges Flittchen Aus Flensburg Outdoor In Den Arsch Gefickt, Asa Akira Couch, Brother Sister Anal, Blojob Porno, Xxx Alt Und Jung, Bbw Brueste, Nude Hausfrau, Sex In Elmshorn, Suesse Freundin, Sex Shop Herne, Brutaler Hentai, Sex In Lichtenfels, Deutscher Model Scout Greift Sich Teenie Engel Zum Ficken, Sexy Lady Porn, Hentai Comics Online, Taboo Sex Porn Tube, Arschlecken Sex, Bdsm Titten Abbinden, Blowjob Fuer Muschi Wichsen, Escort Saarland, Kylie Minogue Porn, Domina Eier, Solo Milfs, Wichsen Privat, Top Bewertete Videos Von Tag Kitzler Fingern, Dlakave Picke, Free Sex Tube Videos, Bdsm Bock, Maschasche, Gierige Oma Ritze Wird Geil Gestopft, Natalie Lust Hd, Two Cocks In One Pussy, German Anal Movie, Nackte Knackaersche, Xhamster Mollig, Geile Hausfrauen, Queenparis Twitter, Ao Porn, Katy Annxo, Amateur Anal Fisting, Whatsapp Porn, Duesseldorf Swinger, Milf Kommt, Keuln Huren, German Mom Teach Step Dperiod, Deutsche Mutter Zum Privat Video Ueberredet, Dicke Milf Fickt, Foot Porno, Blase Gerne, Geile Maedels Ficken, Deutscher Softporno, Verfuehrerische Blonde Hacke Nina Elle Bekommt Ihr Rasierte Moese Haemmerte Sowie, Emma Starr Pornos Sexfilme Kostenlos Frauporno, Michelle Monaghan Sex Consumindo API REST com Ionic - O guia absolutamente completo - Fábrica de Código

Fábrica de Código

Nessa vídeo aula eu vou mostrar como fazer requisições HTTP a uma API REST.
Esse exemplo é valido tanto para aplicações feitas com Angular e Ionic.
E também como paginar os resultados utilizando o InfiniteScroll.

 

O que é API REST

REST significa Representational State Transfer, em português Transferência de Estado Representacional e é um conjunto arquiteturas mais moderno para construção de webservices.

 

Criando uma aplicação de exemplo

Será criado uma aplicação onde eu vou mostrar como criar uma conta, efetuar um login e incluir/alterar/excluir/consultar um usuário.

Vou usar também a API Reqres que prove vários exemplos de endpoints com dados fake.

E vou mostrar como paginar os dados utilizando o componente InfiniteScroll do Ionic.

O passo a passo abaixo é o mesmo mostrado no vídeo.

  • Passo 1: Criar o aplicativo.
  • Passo 2: Configurar o aplicativo para requisições HTTP.
  • Passo 3: Ajustar a Home para exibir os botões para os exemplos.
  • Passo 4: Criar o provider a criação de conta/login/CRUD de usuários.
  • Passo 5: Criar a página de criação de conta
  • Passo 6: Criar a página de login.
  • Passo 7: Criar a página para listar usuários.
  • Passo 8: Criar a página para incluir/alterar um usuário.
  • Passo 9: Criar a pagina para exibir um usuário.

 

Passo 1: Criar o aplicativo

ionic start NOME_DO_APP blank

 

Passo 2: Configurar o aplicativo para requisições HTTP

Registrar o HttpModule na parte de imports.

Arquivo app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { UsersProvider } from '../providers/users/users';

import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    UsersProvider
  ]
})
export class AppModule {}

 

Passo 3: Ajustar a Home para exibir os botões para os exemplos

Arquivo home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) { }

  openCreateAccount() {
    this.navCtrl.push('CreateAccountPage');
  }

  openLogin() {
    this.navCtrl.push('LoginPage');
  }

  openListUsers() {
    this.navCtrl.push('UserListPage');
  }
}

 

Arquivo home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <h1 text-center margin-bottom>Exemplo de API REST</h1>

  <button ion-button block (click)="openCreateAccount()">Criar conta</button>
  <button ion-button block (click)="openLogin()">Login</button>
  <button ion-button block (click)="openListUsers()">CRUD de usuários</button>

</ion-content>

 

Passo 4: Criar o provider a criação de conta/login/CRUD de usuários

ionic g provider users

 

Arquivo users.ts

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

@Injectable()
export class UsersProvider {
  private API_URL = 'https://reqres.in/api/'

  constructor(public http: Http) { }

  createAccount(email: string, password: string) {
    return new Promise((resolve, reject) => {
      var data = {
        email: email,
        password: password
      };

      this.http.post(this.API_URL + 'register', data)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  login(email: string, password: string) {
    return new Promise((resolve, reject) => {
      var data = {
        email: email,
        password: password
      };

      this.http.post(this.API_URL + 'login', data)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  getAll(page: number) {
    return new Promise((resolve, reject) => {

      let url = this.API_URL + 'users/?per_page=10&page=' + page;

      this.http.get(url)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  get(id: number) {
    return new Promise((resolve, reject) => {
      let url = this.API_URL + 'users/' + id;

      this.http.get(url)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  insert(user: any) {
    return new Promise((resolve, reject) => {
      let url = this.API_URL + 'users/';

      this.http.post(url, user)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  update(user: any) {
    return new Promise((resolve, reject) => {
      let url = this.API_URL + 'users/' + user.id;
      let data = {
        "first_name": user.first_name,
        "last_name": user.last_name
      }

      this.http.put(url, user)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }

  remove(id: number) {
    return new Promise((resolve, reject) => {
      let url = this.API_URL + 'users/' + id;

      this.http.delete(url)
        .subscribe((result: any) => {
          resolve(result.json());
        },
        (error) => {
          reject(error.json());
        });
    });
  }
}

 

Passo 5: Criar a página de criação de conta

ionic g page create-account

 

Arquivo create-account.ts

import { UsersProvider } from './../../providers/users/users';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-create-account',
  templateUrl: 'create-account.html',
})
export class CreateAccountPage {
  model: User;

  constructor(public navCtrl: NavController, public navParams: NavParams, private toast: ToastController, private userProvider: UsersProvider) {
    this.model = new User();
    this.model.email = 'sydney@fife';
    this.model.password = 'pistol';
  }

  createAccount() {
    this.userProvider.createAccount(this.model.email, this.model.password)
      .then((result: any) => {
        this.toast.create({ message: 'Usuário criado com sucesso. Token: ' + result.token, position: 'botton', duration: 3000 }).present();

        //Salvar o token no Ionic Storage para usar em futuras requisições.
        //Redirecionar o usuario para outra tela usando o navCtrl
        //this.navCtrl.pop();
        //this.navCtrl.setRoot()
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao criar o usuário. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });
  }
}

export class User {
  email: string;
  password: string;
}

 

Arquivo create-account.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <h1 text-center>Exemplo de criação de conta</h1>

  <ion-list>
    <ion-item>
      <ion-label stacked>Email</ion-label>
      <ion-input type="text" name="email" [(ngModel)]="model.email"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label stacked>Senha</ion-label>
      <ion-input type="password" name="password" [(ngModel)]="model.password"></ion-input>
    </ion-item>
  </ion-list>

  <button ion-button block (click)="createAccount()" color="primary">Criar conta</button>

</ion-content>

 

Passo 6: Criar a página de login

ionic g page login

 

Arquivo login.ts

import { UsersProvider } from './../../providers/users/users';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  model: User;

  constructor(public navCtrl: NavController, public navParams: NavParams, private toast: ToastController, private userProvider: UsersProvider) {
    this.model = new User();
    this.model.email = 'sydney@fife';
    this.model.password = 'pistol';
  }

  login() {
    this.userProvider.login(this.model.email, this.model.password)
      .then((result: any) => {
        this.toast.create({ message: 'Usuário logado com sucesso. Token: ' + result.token, position: 'botton', duration: 3000 }).present();

        //Salvar o token no Ionic Storage para usar em futuras requisições.
        //Redirecionar o usuario para outra tela usando o navCtrl
        //this.navCtrl.pop();
        //this.navCtrl.setRoot()
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao efetuar login. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });
  }
}

export class User {
  email: string;
  password: string;
}

 

Arquivo login.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <h1>Exemplo de login</h1>

  <ion-list>
    <ion-item>
      <ion-label stacked>Email</ion-label>
      <ion-input type="text" name="email" [(ngModel)]="model.email"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label stacked>Senha</ion-label>
      <ion-input type="password" name="password" [(ngModel)]="model.password"></ion-input>
    </ion-item>
  </ion-list>

  <button ion-button block (click)="login()" color="primary">Logar</button>

</ion-content>

 

Passo 7: Criar a página para listar usuários

ionic g page user-list

 

Arquivo user-list.ts

import { UsersProvider } from './../../providers/users/users';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, InfiniteScroll } from 'ionic-angular';
import { ViewChild } from '@angular/core';

@IonicPage()
@Component({
  selector: 'page-user-list',
  templateUrl: 'user-list.html',
})
export class UserListPage {
  users: any[];
  page: number;
  @ViewChild(InfiniteScroll) infiniteScroll: InfiniteScroll;

  constructor(public navCtrl: NavController, public navParams: NavParams, private toast: ToastController, private userProvider: UsersProvider) { }

  ionViewDidEnter() {
    this.users = [];
    this.page = 1;
    this.infiniteScroll.enable(true);
    this.getAllUsers(this.page);
  }

  getAllUsers(page: number) {
    this.userProvider.getAll(page)
      .then((result: any) => {
        for (var i = 0; i < result.data.length; i++) {
          var user = result.data[i];
          this.users.push(user);
        }

        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
          if (this.users.length == result.total) {
            this.infiniteScroll.enable(false);
          }
        }
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao listar os usuários. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });
  }

  getUsers() {
    setTimeout(() => {
      this.page += 1;
      this.getAllUsers(this.page);
    }, 500);
  }

  openUser(id: number) {
    this.userProvider.get(id)
      .then((result: any) => {
        this.navCtrl.push('UserDetailPage', { user: result.data });
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao recuperar o usuário. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });

  }

  openCreateUser() {
    this.navCtrl.push('UserEditPage');
  }

  openEditUser(id: number) {
    this.userProvider.get(id)
      .then((result: any) => {
        this.navCtrl.push('UserEditPage', { user: result.data });
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao recuperar o usuário. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });
  }

  deleteUser(user: any) {
    this.userProvider.remove(user.id)
      .then((result: any) => {
        let index = this.users.indexOf(user);
        this.users.splice(index, 1);

        this.toast.create({ message: 'Usuário excluído com sucesso.', position: 'botton', duration: 3000 }).present();
      })
      .catch((error: any) => {
        this.toast.create({ message: 'Erro ao excluir o usuário. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      });
  }
}

 

Arquivo user-list.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-list>
    <ion-item-sliding *ngFor="let user of users">
      <ion-item (click)="openUser(user.id)">
        <ion-avatar item-start>
          <img src="{{ user.avatar }}">
        </ion-avatar>
        <h2>{{ user.first_name }} {{ user.last_name }}</h2>
      </ion-item>

      <ion-item-options side="left">
        <button ion-button color="primary" (click)="openEditUser(user.id)">
            <ion-icon name="create"></ion-icon>
            Editar
          </button>
        <button ion-button color="danger" (click)="deleteUser(user)">
            <ion-icon name="trash"></ion-icon>
            Excluir
          </button>
      </ion-item-options>
    </ion-item-sliding>

  </ion-list>

  <ion-infinite-scroll (ionInfinite)="getUsers($event)">
    <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Aguarde...">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>

  <ion-fab right bottom>
    <button ion-fab color="light" (click)="openCreateUser()"><ion-icon name="add"></ion-icon></button>
  </ion-fab>
</ion-content>

 

Passo 8: Criar a página para incluir/alterar um usuário

ionic g page user-edit

 

Arquivo user-edit.ts

import { UsersProvider } from './../../providers/users/users';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-user-edit',
  templateUrl: 'user-edit.html',
})
export class UserEditPage {
  model: User;

  constructor(public navCtrl: NavController, public navParams: NavParams, private toast: ToastController, private userProvider: UsersProvider ) {
    if (this.navParams.data.user) {
      this.model = this.navParams.data.user;
    } else {
      this.model = new User();
    }
  }

  save() {
    this.saveUser()
      .then(() => {
        this.toast.create({ message: 'Usuário salvo com sucesso.', position: 'botton', duration: 3000 }).present();
        this.navCtrl.pop();
      })
      .catch((error) => {
        this.toast.create({ message: 'Erro ao salvar o usuário. Erro: ' + error.error, position: 'botton', duration: 3000 }).present();
      })
  }

  private saveUser() {
    if (this.model.id) {
      return this.userProvider.update(this.model);
    } else {
      return this.userProvider.insert(this.model);
    }
  }

}

export class User {
  id: number;
  first_name: string;
  last_name: string;
}

 

Arquivo user-edit.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-list>
    <ion-item>
      <ion-label stacked>Nome</ion-label>
      <ion-input type="text" name="first_name" [(ngModel)]="model.first_name"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label stacked>Sobrenome</ion-label>
      <ion-input type="text" name="last_name" [(ngModel)]="model.last_name"></ion-input>
    </ion-item>
  </ion-list>

  <button ion-button block (click)="save()" color="primary">Salvar</button>

</ion-content>

 

Passo 9: Criar a pagina para exibir um usuário

ionic g page user-detail

 

Arquivo user-detail.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-user-detail',
  templateUrl: 'user-detail.html',
})
export class UserDetailPage {
  user: any;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.user = this.navParams.data.user;
  }

}

 

Arquivo user-detail.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Rest Api Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <div text-center>
      <img src="{{ user.avatar }}">
    <h1>{{ user.first_name }} {{ user.last_name }}</h1>
  </div>
</ion-content>

 

Clique no botão abaixo para ver o código fonte gerado nessa aula

 

[button style=”btn-primary btn-lg” type=”link” target=”true” title=”Código fonte gerado na aula” link=”https://github.com/fabricadecodigo/IonicConsumeRestApiExample” linkrel=””]

 

Referências

 

Gostou desse artigo? Aproveite e curta e compartilhe para que mais pessoas possam também visualiza-lo!

Ainda ficou alguma dúvida ou tem alguma sugestão? Deixa aí nos comentários!

Respostas de 11

  1. Adorei o site, tudo que eu estava precisando para iniciar no ionic,
    Parabéns.

  2. olá boa noite, muito bom material…
    só fiquei com uma duvida, como pego os dados vindo do form, no caso os this.model.email = ‘sydney@fife’; this.model.password = ‘pistol’;

  3. Muito boa a aula Felipe.

    Poderia me dar um help?
    Estou tendo este erro ao rodar a aplicação.

    Error: Uncaught (in promise): invalid link: CreateAccountPage
    at c (http://localhost:8100/build/polyfills.js:3:19752)
    at Object.reject (http://localhost:8100/build/polyfills.js:3:19174)
    at NavControllerBase._fireError (http://localhost:8100/build/vendor.js:48008:16)
    at NavControllerBase._failed (http://localhost:8100/build/vendor.js:48001:14)
    at http://localhost:8100/build/vendor.js:48048:59
    at t.invoke (http://localhost:8100/build/polyfills.js:3:14976)
    at Object.onInvoke (http://localhost:8100/build/vendor.js:4979:33)
    at t.invoke (http://localhost:8100/build/polyfills.js:3:14916)
    at r.run (http://localhost:8100/build/polyfills.js:3:10143)
    at http://localhost:8100/build/polyfills.js:3:20242
    Ionic Framework: 3.9.2

  4. Fala Leonay, desculpa não responder antes, apenas hoje vi seu comentário.
    De qualquer maneira,

    Tanto para pegar, como para passar os dados para o formulário é só preencher as propriedades que vão no [(ngModel)], no exemplo desse artigo estou usando a propriedade model, então ficaria this.model.email, exatamente como estou usando no método createAccount da página CreateAccountPage.

    Se eu não tivesse criado o código

    this.model.email = ‘sydney@fife’;
    this.model.password = ‘pistol’;

    Quando o clicasse no botão para criar a conta eu iria conseguir acessar os valores digitados no formulário através do this.model.email ou this.model.password

    Valeu!

  5. Conteúdo muito bom, aproveito aqui para compartilhar minha experiência com o ionic, desenvolvi dois aplicativos hibridos, um é um jogo da memória onde vc mesmo cria seus tabuleiros com suas imagens de galeria, se quiserem dar uma olhada e me dar a opinião de vcs, está na playstore e é gratuito, segue o link =)
    https://play.google.com/store/apps/details?id=com.i9.memoriav1
    o outro é um aplicativo para vendedores criarem seus catalogos de produtos:
    https://play.google.com/store/apps/details?id=com.i9.catalogov1

  6. Muito bom amigo, podeira fazer um exemplo implementando a função de salvar esses dados em um banco sqlite local pra uso offline caso não tenha conexão??