Majesty
Majesty

Reputation: 1909

Angular2.1 Cannot read property 'get' of undefined

So, I'm currently trying to send a HTTP request, I'm doing everything exactly like in official guide and it's wont work (as usual when you make deal with Angular2)

Here is my app.module

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes }   from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent }   from './app.component';
import { PageComponent } from './modules/Affiliate/affiliate.component';
import { NotFoundComponent }   from './not-found.component';


const routes: Routes =
    [
        { path: 'page', component: PageComponent },
        { path: '404', component: NotFoundComponent },
        { path: '**', redirectTo: '404' }
    ];

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(routes),
        HttpModule,
        JsonpModule
    ],
    declarations: [
        AppComponent,
    ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

And here is my service, where I'm trying to send a http request

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class GridService {
    constructor(private http: Http) { }

    getTableRaws(url): Promise<any> {
            return this.http.get(url)
                .toPromise()
                .then(response => response.json().data as any)
                .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

Any ideas, please

Upvotes: 1

Views: 1292

Answers (2)

Majesty
Majesty

Reputation: 1909

Here is the solution that works for me:

constructor(@Inject(Http) private http: Http) {}

Upvotes: 0

mansoor.khan
mansoor.khan

Reputation: 2616

Following the docs, I guess you missed the data type for the url param:

getTableRaws(url: string): Promise<any> {
...
}

UPDATE:

You need to add GridService as a provider in app.module. Refer to this SO answer.

If you have made these changes then update your code in the question and also provide the contents of app.component here.

Upvotes: 1

Related Questions