Search code examples
apihttpionic-frameworkhttpurlconnectionangular-providers

How to match and validate with the provided API in Ionic?


I have created login function accordingly but the login function is not working. Whenever I enter the sample input (phoneNumber and password) it did not directing me to the HomePage. Details about API has been provided in the pictures below. Is there anything I am missing out? Please HELP me to solve this out.

API details: enter image description here

enter image description here

enter image description here

HTML CODE:

<ion-header>
  <ion-navbar>
    <ion-title>
      Login
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <form name="form"(ngSubmit)="login()" novalidate>
      <ion-item>
        <ion-label fixed>Phone Number</ion-label>
        <ion-input type="number" name="phoneNumber" value="" [(ngModel)]="model.phoneNumber" required></ion-input>
      </ion-item>

      <ion-item>
        <ion-label fixed>Password</ion-label>
        <ion-input type="password" name="password" value="" [(ngModel)]="model.password" required></ion-input>
      </ion-item>
      <ion-item>
        <button ion-button>Enter</button>
      </ion-item>
    </form>
  </ion-list>
</ion-content>

.TS CODE:

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, ToastController } from 'ionic-angular';
import { HomePage } from '../home/home';
import { apiService } from '../../providers/api-service.service';
import { AuthService } from '../../providers/auth-service.service';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})

export class LoginPage {
  model : any = {};
  response: any[] = [];
  constructor(public navCtrl: NavController, public apiService: apiService, public toastCtrl: ToastController, public alertCtrl: AlertController, public loadingCtrl: LoadingController, public AuthService: AuthService){}

  loginUser(){
    this.AuthService.login();
  }
  logoutUser(){
    this.AuthService.logout();
  }
  nextPage(data){
    this.navCtrl.push(HomePage,data).catch(err => {
      let alert = this.alertCtrl.create({
        title: 'Something',
        subTitle: 'something something',
        buttons: ['OK']
      });
      alert.present();
    });
  }
  errorToast(){
    let toast = this.toastCtrl.create({
      message: 'Cannot login',
      duration: 3000
    });
    toast.present();
  }
  logoutout(){
    let loader = this.loadingCtrl.create({
      content: "Loging out.....",
      duration: 1000
    })
    loader.present();
    this.loginUser();
  }
  login(){
    this.apiService.apiCall(this.model.phoneNumber, this.model.password)
    .then(data => {
      this.logoutout();
      this.nextPage(data);
    })
    .catch(error => {
      this.errorToast();
    })
  }
}

PROVIDERS CODE:

api-service.service.ts

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

@Injectable()
export class apiService{
    constructor(private http: Http){}

    apiCall(phoneNumber, password){
        let headers = new Headers({
            "X-Auth-PhoneNumber": '',
            "X-Auth-Password": '',
            "SW-Version": '',
            "Device-Id": '',
            "Device-Model": ''
        })
        let options = new RequestOptions({
            headers: headers
        });

        return this.http.get('https://api.keyway.com.my/client/mobile/verification'+ phoneNumber + password, options)
        .map(res => res.json())
        .toPromise();
    }
}

auth-service.service.ts

import {Injectable} from '@angular/core';
@Injectable()
export class AuthService{
    private isLoggedIn = false;
    constructor(){}

    login(): void{
        this.isLoggedIn = true;
    }
    logout(): void{
        this.isLoggedIn = false;
    }
    authenticated():boolean{
        return this.isLoggedIn;
    }
}


Solution

  • Because you are sending username and password with request URL but as per request defination you need to send in headers so,please made some changes like below -

    apiCall(phoneNumber, password){
            let headers = new Headers({
                "X-Auth-PhoneNumber": phoneNumber',
                "X-Auth-Password": password,
                "SW-Version": '',
                "Device-Id": '',
                "Device-Model": ''
            })
            let options = new RequestOptions({
                headers: headers
            });
    
            return this.http.get('https://api.keyway.com.my/client/mobile/verification', options)
            .map(res => res.json())
            .toPromise();
        }
    

    Also try to console output after request.

    login(){
        this.apiService.apiCall(this.model.phoneNumber, this.model.password)
        .then(data => {
          console.log(data);    // Console Output
          this.logoutout();
          this.nextPage(data);
        })
        .catch(error => {
          console.log(error);    // Console Error output
          this.errorToast();
        })
      }