How to pass parameters from Login page!

I have a login page but i do not know how to pass certain parameters after subscribing and receiving data. Also I don’t know how and where to check the received data…if login is true , push (this) if not (log error) ???

login.ts

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

            login: {username?: string , password?: string} = {};
            submitted = false;


            constructor(public navCtrl: NavController, private schoolAppUsers: SchoolAppUsers) {

            this.schoolAppUsers=schoolAppUsers;
 
         } 

                onLogin(form) {

                   this.submitted = true;
  
                   if (form.valid) {
    
                   this.schoolAppUsers.login(this.login).subscribe(loginDetails => {
  
                   this.navCtrl.setRoot(TeachersPage);
                   });   
                 }
              }
           }

service.ts

       @Injectable()
       export class SchoolAppUsers {
       loginApiUrl = 'http://localhost/SchoolApp/include/userLogin.php';
       
        login(login): Observable<User> {
           let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
           let options = new RequestOptions({ headers: headers });

           return this.http.post(this.loginApiUrl,'username='+login.username+'&password='+login.password, options)
  .map(res => <User>(res.json()))

        }
       }

When I console log (loginDetails) , I see that I am receiving the right details, but how and where Do I write the conditions to act accordingly before setting or pushing the next page ??

Also when the user login , there is column specified for user role / user type … How do I pass this information along to use it in other pages…because I have 3 different users that have different access (admin , student, lecturer)

can someone please enlighten me on this issue , much appreciated.

I think you can convert observable to promise and use then/catch for your purpose:

Service:

login(login): Promise<User> {
           let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
           let options = new RequestOptions({ headers: headers });

           return this.http.post(this.loginApiUrl,'username='+login.username+'&password='+login.password, options)
               .toPromise()
               .then(res => res.json())
        }

Component:

onLogin(form) {
    this.submitted = true;
    if (form.valid) {
        this.schoolAppUsers.login(this.login)
           .then(loginDetails => this.navCtrl.setRoot(TeachersPage)) // if you don't need to check or some action with loginDetails - just return navCtrl
           .catch(error => console.log('Auth error: ', error));
    }
}

You can pass params from login page to next in navCtrl params

.then(loginDetails => this.navCtrl.setRoot(TeachersPage, {loginParams: loginDetails}))

and catch params on TeachersPage with NavParams instance

import { OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';

export class TeachersPage implements OnInit {
    public loginParams: User;

    constructor(
        private params: NavParams
    ) { }

    public ngOnInit(): void {
        this.loginParams = this.params.get('loginParams');
    }

    public dismiss(): void {
        this.viewCtrl.dismiss();
    }
}

But if more than one page required loginParams, you can use service for it:

'use strict';

import { Injectable } from '@angular/core';

@Injectable()
export class GlobalsService {
    private $rootScope: any;

    constructor() {
        this.$rootScope = {};
    }

    public get(name: string): any {
        return this.$rootScope[name];
    }

    public set(name: string, value: any): void {
        this.$rootScope[name] = JSON.parse(JSON.stringify(value)); // for array and objects copy
    }

    public setCircular(name: string, value: any): void {
        this.$rootScope[name] = value; // JSON hack will not work here
    }

    public assign(name: string, value: any): void {
        var data = this.get(name) || {};
        data = Object.assign(data, value);
        this.set(name, data);
    }

    public clear(name?: string): void {
        if (name) {
            delete this.$rootScope[name];
        } else {
            this.$rootScope = {};
        }
    }
}

And in component:

onLogin(form) {
    this.submitted = true;
    if (form.valid) {
        this.schoolAppUsers.login(this.login)
           .then(loginDetails => this.globals.set('loginDetails', loginDetails)
           .then(()=> this.navCtrl.setRoot(TeachersPage))
           .catch(error => console.log('Auth error: ', error));
    }
}

And on other pages

import { OnInit } from '@angular/core';
import { NavParams } from 'ionic-angular';

export class TeachersPage implements OnInit {
    public loginParams: User;

    constructor(
        private globals: GlobalsService
    ) { }

    public ngOnInit(): void {
        this.loginParams = this.globals.get('loginParams');
    }

    public dismiss(): void {
        this.viewCtrl.dismiss();
    }
}

P.S: Code can contain errors, I write it without IDE

Thank you snikh for your reply
my side-server already returning appropriate responses: if username and password are true , it will return user data , if not , it will return an error message…

I think i need to check (loginDetails) because it has the response
.then(loginDetails => this.navCtrl.setRoot(TeachersPage))

so how do i do that ?
I tried accessing loginDetails like this ==> loginDetails.role … but it didnt work out

my returned json data is like this: when I console.log(loginDetails);

error: "false"
name: "abs"
username: "abs12"
password: "123"
role: “1” >>> for admin

error: "true"
message: “wrong username or password”

I think that this is bad practice. Server side must return correct response status (200, 401, 403 etc). And angular automatically split your response on good (then) and bad (catch).

But if you can’t change server side:

(NOTE: I rewrite my post above and show how to save params for different page)

onLogin(form) {
    this.submitted = true;
    if (form.valid) {
        this.schoolAppUsers.login(this.login)
           .then(loginDetails => {
                this.globals.set('loginDetails', loginDetails); // save details for other pages
                if (loginDetails.role === '1') {
                    return this.navCtrl.setRoot(AdminPage);
                } else {
                   return this.navCtrl.setRoot(TeachersPage);
                }
        });
    }
}

I see , i will try to change my server side , even though im weak in php, weak in all actually

Thank you for you help , much appreciated :slight_smile:

mr. snikh

I keep receiving typescript error on : if (loginDetails.role === ‘1’)
Operator ‘===’ cannot be applied to types ‘number’ and ‘string’
??

Your loginDetails.role type set to number. But according to your console log, it’s string. So change it (User interface, field role).
Or you can change condition to

if (+loginDetails.role === 1)

hmm unfortunately , the problem still persists…

Not recommended, but you can try dirty hack

if ((<any>loginDetails).role === 1)

also , when i console.log(loginDetails.role)
I get ‘undefined’

this.schoolAppUsers.login(this.login)
.then(loginDetails => {
console.log(loginDetails.role);
});
}

Probably problem in your schoolAppUsers service.
Check console.log(res) and console.log(res.json()) in it.

the dirty hack maybe working… however after clicking Login button , it does not redirect to the page return this.navCtrl.setRoot(TeachersPage);
I checked the “Network” i receive response from php and user data

the problem is , I cannot access “role” by loginDetails.role
even though console.log(loginDetails) does return json data
"error": “false”
“name”: “abs”
“username”: "abs12"
“password”: "123"
“role”: 1

     this.schoolAppUsers.login(this.login)
           .then(loginDetails => {
           console.log(loginDetails);  // returns json data
           console.log(loginDetails.role);  // undefined

      if ((<any>loginDetails).role === 1) {
        return this.navCtrl.setRoot(TeachersPage);
      }
  });

It’s some kind of magic :slight_smile:

Maybe loginDetails return JSON stringified data? Check

console.log(typeof loginDetails);

if return string, then

loginDetails = JSON.parse(loginDetails);

If return object, than it definitely magic.

it returns object

im about to cry lol

Hmm…maybe object keys contain non ASCII symbols? Try to copy role text field from console and replace on it in your

console.log(loginDetails.role);

Also add debugger after console.log and check in browser your object fields.

you can check object fields by console.log(JSON.stringify(loginDetails))

everything seems fine

[{“error”:“false”,“UserID”:1,“name”:“yasir”,“username”:“yasir12”,“password”:“123”,“role”:1}]

nope… your login details object is inside an array. you have to do loginDetails[0].role to fetch it