Smokey
Smokey

Reputation: 1897

ionic2- response from http request is shown as undefined

I created a provider having many functions and each of them performs an HTTP request to the API server. I updated app.module.ts after creating the provider.

I'm trying to return the data obtained from the api services to the page where this provider is injected.

Here's my provider:

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

@Injectable()
export class LoginServicesProvider {
  apiUrl: string = 'API URL COMES HERE';
  constructor(public http: Http) {
  }

  login(reqData) {
    this.http.post(apiUrl+'/checkLogin', reqData).map(res => res.json()).subscribe(data => {
      return data;
    });
  }

}

This is where this provider is injected:

import { LoginServicesProvider } from './../../providers/login-services/login-services';
import { Http } from '@angular/http';
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';

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

  loginServiceData: Observable<any>;
  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    private http: Http,
    private loginService: LoginServicesProvider
    ) 
    {  
        let userName: string = 'dumy_user_name';
        let userPassword: string = '12345';
        let data = {
            username: userName,
            password: userPassword,
        };

        this.loginServiceData = this.loginService.login(data);
        console.log(this.loginServiceData);      
    }
}

When I run the project, http is made but I'm getting undefined when I console.log() it. API is returning an object.

Can anyone tell what's the mistake I made.

ionic info returns this:

cli packages: (C:\Users\Demo\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : not installed

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3 browser 5.0.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v6.12.0
    npm               : 5.6.0
    OS                : Windows 10 

Upvotes: 1

Views: 474

Answers (1)

Dhyey
Dhyey

Reputation: 4335

An API call is asynchronous but you are trying to do it synchronously

In your service you don't need to subscribe, just return the Observable and subscribe to it in the component file

Service file:

login(reqData) {
    return this.http.post(apiUrl+'/checkLogin', reqData).map(res => res.json())
}

Component File:

this.loginService.login(data).subscribe((data: any) => {
    this.loginServiceData = data;
    console.log(this.loginServiceData);      
})

Now you will be able to see the proper object in your console.

Upvotes: 1

Related Questions