Search code examples
angularangular2-services

Angular 2 HTTP Request: TypeError: backend.createConnection is not a function


I'm trying to run a simple HTTP request in Angular and am running into the following error:

angular2.dev.js:23941 Error: Uncaught (in promise): EXCEPTION: Error during instantiation of AlbumListComponent!. ORIGINAL EXCEPTION: TypeError: backend.createConnection is not a function

To simplify I broke down the HTTP functionality to its simplest removing the service and just directly accessing the HTTP service and Observable:

import {Component} from 'angular2/core';
import {Album} from './album';
import {AppState} from './appstate'; 
import {Observable}     from 'rxjs/Observable';

import {Http}    from 'angular2/http';

@Component({
    selector: 'album-list',
    templateUrl: 'Views/albumList.html',
    providers: [AlbumService, Http, Response]        
})
export class AlbumListComponent {
    albums: Array<Album> = [];
    title: string = "Album Listing";
    errorMessage: string;


    constructor(public state: AppState,
        public albumService: AlbumService,
        public http: Http) {

        console.log('AlbumList Constructor' +  this.title);
        state.activeTab = "albums";
        debugger;

        http.get(state.urls.albums)
            .map(res => {
                debugger;
                return res.json()
            })
            //.catch(error => {
            //    debugger;
            //    console.error(error);
            //    return Observable.throw(error.json().error || 'Server error');
            //})
            .subscribe(albums => this.albums = albums)           

        //this.getAlbums();  // service removed to simplify
    }


}

Bootstrap code (and http.dev.js is included in the script list):

import {bootstrap}    from 'angular2/platform/browser';
import {Albumviewer} from './albumviewer.component';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppState} from './appstate'
import 'rxjs/Rx';

bootstrap(Albumviewer,[
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
]);

I either get the described error, or errors about missing providers (like ConnectionBackend).

If I remove the Http access code the app runs OK. With the code in there it bombs. I have no idea what to look at here - as the error message clearly refers to a child component used by the HTTP service.


Solution

  • update

    In Angular2 final adding HttpModule to imports of @NgModule() does the same

    original

    You don't show your bootstrap(...) but it probably doesn't contain HTTP_PROVIDERS

    bootstrap(AppComponent, [HTTP_PROVIDERS]);
    

    HTTP_PROVIDERS contains Http and all its dependencies. If you add HTTP_PROVIDERS to bootstrap() there is no need to add Http to providers on components because this way it is made globally available.

    You still need to import it if you want to inject it though.