0

I have an ionic 2 app that I've been testing using local data. Now, I am attempting to make some Ajax requests to my api to get the data.

In my app.js file, I am defining my component like so:

import {UserProvider} from './providers/user-provider';
...
    @App({
      templateUrl: 'build/app.html',
      providers: [UserProvider]
    })

Then, my user-provider.js file is defined like so:

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

@Injectable()
export class UserProvider {
    constructor(http: Http) {
        http.get('www.someURL.com').toRx().map(res => res.json())
            .subscribe(data => console.log(data));
    }
}

Then, lastly, I am initializing my "Sign Up" view with my signup.js file:

import {Page, NavController} from 'ionic/ionic';
import {TabsPage} from '../tabs/tabs';
import {UserProvider} from '../../providers/user-provider';

@Page({
  templateUrl: 'build/pages/signup/signup.html'
})
export class SignupPage {
  constructor(nav: NavController, userProvider: UserProvider) {
    this.userProvider = userProvider;
    this.nav = nav;
  }
}

My expected result is that on initialization of my signup view, the UserProvider will be injected. As such, it's constructor will run, which will fire off the http.get function within the UserProvider's constructor. I should then see a network call in my browsers network tab.

However, I'm getting this error:

EXCEPTION: Error during instantiation of UserProvider! (SignupPage -> UserProvider)

app.bundle.js:33693 TypeError: http.get(...).toRx is not a function
    at new UserProvider (app.bundle.js:60706)

Why is http.get.toRx() causing an error? I initially tried this with promises like so:

http.get('www.someURL.com').then(() => {
            console.log('test');
        });

but that throws a similar error.

JMac
  • 1,726
  • 3
  • 14
  • 30

1 Answers1

2

In angular2-beta0 http.get() already returns an Observable, you don't need to call its former .toRx() method, you can just directly call .map() and such.

Ionut Costica
  • 1,382
  • 1
  • 9
  • 19
  • 1
    Interesting - So, calling `.map` directly gives me this error: `TypeError: http.get(...).map is not a function` Is there an issue with the importing of the `http` component? Should it be included elsewhere maybe? I initially thought it had to be included in the `bootstrap` function call, but my ionic (cordova) app doesn't use the `bootstrap` function. – JMac Jan 04 '16 at 03:00
  • 2
    The `.map()` Rx function probably has to be imported. See the answer at http://stackoverflow.com/questions/34581471/angular2-http-is-missing-map-function for more information. It's possible that a `import 'rxjs/add/operator/map';` would be sufficient if everything else is set up correctly. – Ionut Costica Jan 04 '16 at 03:15