Pada kesempatan ini, saya akan berbagi ilmu tentang cara membuat halaman login ionic integrasi dengan PHP dan Mysql.
Membuat Login Ionic Integrasi PHP dan Mysql
Sebelum memulai membuat aplikasi Ionic, pertama kita buat database terlebih dahulu. Contoh database bernama loginionic, untuk tabelnya kita buat tabel bernama users.
Baca juga Membuat Login dan Register Ionic 4
Tabel Users
CREATE TABLE `users` (
`id_users` int(11) AUTO_INCREMENT,
`username` varchar(50),
`password` varchar(100),
`nama` varchar(100),
`email` varchar(200),
PRIMARY KEY (`id_users`)
);
Buat rest api menggunakan slim framework. Rest api ini berguna untuk menghubungkan aplikasi dengan database. Untuk lebih jelasnya silahkan download filenya https://github.com/Rest-Api-Login-Ionic
index.php
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Content-Type: application/json');
require 'config.php';
require 'vendor/autoload.php';
$app = new Slim\App();
$app->post('/login','login');
$app->run();
function login($request, $response) {
$data = $request->getParsedBody();
try {
$db = getDB();
$userData ='';
$sql = "SELECT username, nama, email FROM users WHERE username=:username and password=:password";
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $data['username'], PDO::PARAM_STR);
$stmt->bindParam("password", $data['password'], PDO::PARAM_STR);
$stmt->execute();
$mainCount=$stmt->rowCount();
$userData = $stmt->fetch(PDO::FETCH_OBJ);
if(!empty($userData))
{
$username=$userData->username;
$userData->token = apiToken($username);
}
$db = null;
if($userData){
$userData = json_encode($userData);
echo '{"userData": ' .$userData . '}';
} else {
echo '{"error":{"text":"Bad request wrong username and password"}}';
}
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Buat project baru
ionic start LoginApp blank
Masuk ke directory aplikasi yang telah dibuat, kemudian buatlah provider dengan nama authService
ionic g provider authService
authService.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
let apiUrl = 'http://localhost/loginionic/';
@Injectable()
export class AuthServiceProvider {
constructor(public http : Http) {
// console.log('Hello AuthServiceProvider Provider');
}
postData(credentials, type) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(apiUrl + type, JSON.stringify(credentials), options)
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
app.module.ts
buka app.module.ts yang berada pada src/app/app.module.ts, kemudian import AuthServiceProvider dan HttpModule
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 { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { AuthServiceProvider } from '../providers/auth-service/auth-service';
@NgModule({
declarations: [
MyApp,
HomePage,
LoginPage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
LoginPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AuthServiceProvider
]
})
export class AppModule {}
Buatlah halaman login
ionic g page login
login.html
<ion-header>
<ion-navbar>
<ion-title>login</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="FormLogin" (ngSubmit)="login()">
<ion-item >
<ion-label color="primary" stacked>Username</ion-label>
<ion-input type="text" formControlName="username" ></ion-input>
</ion-item>
<ion-item >
<ion-label color="primary" stacked>Password</ion-label>
<ion-input type="password" formControlName="password" ></ion-input>
</ion-item>
<ion-item>
<button ion-button full type="submit" color="secondary" [disabled]="!FormLogin.valid" >Login</button>
</ion-item>
</form>
</ion-content>
login.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { Validators,FormBuilder,FormGroup } from '@angular/forms';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
import { HomePage } from '../../pages/home/home';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
private FormLogin:FormGroup;
responseData : any;
userData = {"username": "","password": "", "nama": ""};
constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder:FormBuilder,
public authService:AuthServiceProvider, public toastCtrl: ToastController) {
this.FormLogin=this.formBuilder.group({
username:['', Validators.required],
password:['', Validators.required]
});
}
login(){
this.authService.postData(this.FormLogin.value,'login').then((result) => {
this.responseData = result;
if(this.responseData.userData){
localStorage.setItem('userData', JSON.stringify(this.responseData));
this.navCtrl.push(HomePage);
}
else{
const toast = this.toastCtrl.create({
message: 'Nama pengguna dan kata sandi yang Anda masukkan tidak cocok. Silakan periksa dan coba lagi.',
duration: 3000
});
toast.present();
}
}, (err) => {
});
}
}
Terakhir ubah app.component.ts untuk mengkondisikan apakah user sudah login
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
statusBar.styleDefault();
//cek storage
if(localStorage.getItem('userData')==null) {
this.rootPage = LoginPage;
}else{
this.rootPage = HomePage;
}
splashScreen.hide();
});
}
}
Source code:
loginApp.rar
Related Search:
- Membuat login ionic dengan php mysql
- Membuat login ionic dengan rest api php
- login ionic dengan php mysql