1
votes

I am using Angular 2.0 beta version. I need to call a web API from a service. But I didn't get any solution.

mobileService.ts

import {Http, Headers, HTTP_PROVIDERS} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import { Mobile } from './datatypes/Mobile';

@Injectable()
export class MobileService {          
     constructor(public http: Http) {     
        this.http = http;
        }

getMobiles() {        
    // return an observable
    return this.http.get("api/ElectronicsAPI/Get")
        .map((responseData) => {
            return responseData.json();
        })
        .map((mobiles: Array<any>) => {
            let result: Array<Mobile> = [];
            if (mobiles) {
                mobiles.forEach((mobile) => {
                    result.push(
                        new Mobile(mobile.name,
                            mobile.price));
                });
            }
            return result;
        });
}
}

Error is,

  • this.http.get(...).map is not a function

Also I haved some questions related to this topics. In that, they mention to import map as,

  • import 'Rxjs/add/operator/map'

But how can I do that in TypeScript?

Is there any other way to import plugin for the map function ?

boot.ts

import {bootstrap}    from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS} from 'angular2/http';

bootstrap(AppComponent,[ROUTER_PROVIDERS,HTTP_PROVIDERS]);
1

1 Answers

1
votes

You can use the following within your mobileService.ts file:

import 'Rxjs/add/operator/map'

This import should be done where you use the map method.

The following answers could help you as well:

Hope it helps you, Thierry