Ad

Ionic 2 - Importing/Injecting Angular 2 HTTP Component

- 1 answer

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad