ORIGINAL EXCEPTION: Cannot read property 'post' of undefined

Hello

if i try post data to server for user credentials with http.post i have error: “Cannot read property ‘post’ of undefined”.

This is part of my code:

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

export class User {
  sessionid: string;
  username: string;

  constructor(sessionid: string, username: string) {
    this.sessionid = sessionid;
    this.username = username;
  }
}

@Injectable()
export class AuthService {
  currentUser: User;
  public jdata: any;
  public _linkLocal = "https://sdfsdffdf";
  public _linkIntranet = "https://isdfsfsfs";
  public http: Http;


  //convert a json object to the url encoded format of key=value&anotherkye=anothervalue
  private jsonToURLEncoded(jsonString) {
    return Object.keys(jsonString).map(function (key) {
      return encodeURIComponent(key) + '=' + encodeURIComponent(jsonString[key]);
    }).join('&');
  }

  public login(credentials) {
    console.log(credentials);
    if (credentials.username === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      let body = this.jsonToURLEncoded({ username: credentials.username, password: credentials.password, deviceid: "this.jdata.deviceid" });
      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      console.log(body);

      this.http.post(this._linkIntranet, body, {
        headers: headers
      })
        .subscribe(data => {
          this.jdata.response = data['_body'];
          console.log(this.jdata.response = data['_body']);
        }, error => {
          console.log(JSON.stringify(error.json()));
        }
        );
    }
  }

image

credentials is a data from login form

Your AuthService has no constructor.

add the following and it should work

constructor(private http: Http) {}

and dont forget to put it in app.modules.ts:

providers [ AuthService ]

Then you can use it in your pages by injecting it into their constructos like the http in the constructor above

ok, i put http to constructor, but not as private (still doesn’t work) only as public. And i have an error when i try subscribe method:

on line:

    .subscribe(data => {
      this.jdata.response = data['_body'];
      console.log(this.jdata.response = data['_body']);
    }, error => {
      console.log(JSON.stringify(error.json()));
    }

Have you injected your AuthService Provider into your LoginPage or how do you create an object from AuthService?

yes, i have imported authservice on login page. below, my login page code

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  loading: Loading;
  registerCredentials = { username: '', password: '' };

  constructor(
    private navCtrl: NavController,
    private auth: AuthService,
    private alertCtrl: AlertController,
    private loadingCtrl: LoadingController
  ) { }

  public createAccount() {
    this.navCtrl.push(RegisterPage);
  }

  public login() {
    this.showLoading()
    this.auth.login(this.registerCredentials).subscribe(allowed => {
      if (allowed) {
        setTimeout(() => {
          this.loading.dismiss();
          this.navCtrl.setRoot(SearchPage);
        });
      } else {
        this.showError("Access Denied");
      }
    },
      error => {
        this.showError(error);
      });
  }

  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: 'Please wait...'
    });
    this.loading.present();
  }

  showError(text) {
    setTimeout(() => {
      this.loading.dismiss();
    });

    let alert = this.alertCtrl.create({
      title: 'Fail',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present(prompt);
  }
}

ok, problem is solved, i moved code with json http.post to observer and then subscribe, this is final function:

  public login(credentials) {
    console.log(credentials);
    if (credentials.username === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      //this.getJsonCredentials(credentials);
      return Observable.create(observer => {

        // At this point make a request to your backend to make a real check!
        let body = this.jsonToURLEncoded({ username: credentials.username, password: credentials.password, deviceid: "this.jdata.deviceid" });
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        console.log(body);

        this.http.post(this._linkIntranet, body, {
          headers: headers
        })
          .subscribe(data => {
            this.data.response = data['_body'];
            console.log(this.data.response);

            let access = (credentials.password === "pass" && credentials.username === "username");
            this.currentUser = new User('user', 'user@mail');
            observer.next(access);
            observer.complete();

          }, error => {
            console.log(JSON.stringify(error.json()));
          }
          );


      });
    }
  }

I don’t understand why you are creating an Observable from scratch instead of returning the one that http gives you.

@rapropos You right, i was checked and http gives observe too