Angular (IONIC) - Cannot read property 'getInfos' of undefined

Viewed 32

I was following a "tutorial" where I can read an API from Angular. When I open my Symfony, I can read the endpoint with a GET and a POST (with Postman too).

  ngOnInit() {
    try {
      return this.infosService.getAllInfos()
          .subscribe(data => this.infos = data);
    } catch(e) {
      console.log("TEST KO");
    }
  }

In my infos.service.ts file, I got these lines to get the datas but only call getAllInfos in this example:

  apiUrl='Http://localhost:8000/api/info';

  constructor(private _http: HttpClient) { }
    getInfos() {
        return this._http.get<Infos[]>(this.apiUrl);
    }

    getAllInfos() {
        return this._http.get<Infos[]>(this.apiUrl);
    }

Thanks: https://stackblitz.com/edit/ionic-hnz4eg?devtoolsheight=33&file=app/infos-render/infos-render.component.html

Where did I mess up?

1 Answers

You didn't import HttpClientModule and not correct InfosService providing in app.module:

import { NgModule, ErrorHandler } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { IonicApp, IonicModule, IonicErrorHandler } from "ionic-angular";
import { MyApp } from "./app.component";
import { HttpClientModule } from "@angular/common/http";

import { AboutPage } from "../pages/about/about";
import { ContactPage } from "../pages/contact/contact";
import { HomePage } from "../pages/home/home";
import { TabsPage } from "../pages/tabs/tabs";
import { InfosService } from "./services/infos/infos.service";
import { InfosRenderComponent } from "./infos-render/infos-render.component";

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    InfosRenderComponent
  ],
  imports: [BrowserModule, IonicModule.forRoot(MyApp), HttpClientModule],
  bootstrap: [IonicApp],
  entryComponents: [MyApp, AboutPage, ContactPage, HomePage, TabsPage],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    InfosService
  ]
})
export class AppModule {}

or you can see full here

Related