Inside the constructor http is undefined


#1

created a simple component to get data

example code:

import {Http} from 'angular2/http';

export class Data {

    static get parameters() {
        return [[Http]];
    }

    constructor(http) {

        **// http is undefined from here**

        this.http = http;

       this.jsonData = this.http.get('http://jsonplaceholder.typicode.com/posts').map(res => res.json());
       console.log(this.jsonData)
    }
}

#2

Your code is… wrong. All what you need:

export class Data {
  constructor(private http:Http) {
    this.http.get('http://jsonplaceholder.typicode.com/posts').map(res => res.json()).subscribe((response: any) => {
      console.log(response)
    });
  }
}

#3

The code looks fine, I can confirm that this works:

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable()
export class Data {

  static get parameters(){
    return [[Http]];
  }

  constructor(http) {
    console.log(http);
    this.http = http;
  }
}

Maybe try updating your CLI and starting a fresh project to see if it works then.


#4

HI joshmorony, could you tell me the CLI version you are running? i am running 2.0.0-beta.19


#5

Same, have you tried running this in a new (beta.3) project?


#6

I created a new project and it worked with 2.0.0-beta.19, a bit frustrating. Not sure why but i will look into a bit more. Thanks for the help


#7

In the case you are using TypeScript, have you tried the @xr0master code?


#8

So there appears to be some confusion. It looks like @Daikinzan started with a regular ES6 project.

So I tried this, and it works fine.

import {Page} from 'ionic-angular';
import {Http} from 'angular2/http';

@Page({
  templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
  static get parameters() {
    return [[Http]];
  }
  constructor(http){
    console.log(http)
  }
}

#9

To confirm, yes it is an ES6 project and the example code submitted by @joshmorony and @mhartington works.