Issue
I am trying to fetch data in ionic from a given URL using the below simple code, but when I try to log the data it gives me undefined, please help.
getcategories.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetcategoriesService {
public categories: any;
constructor(private http: HttpClient) { }
initialize(){
this.getservices().then(data => this.categories = data);
}
getservices(){
const url = 'url goes here';
return this.http.get(url).toPromise();
}
}
services.page.ts
import { Component, OnInit } from '@angular/core';
import {GetcategoriesService} from '../../services/getcategories.service';
import {HttpClientModule} from '@angular/common/http';
@Component({
selector: 'app-services',
templateUrl: './services.page.html',
styleUrls: ['./services.page.scss'],
})
export class ServicesPage implements OnInit {
public data: any ;
constructor( private getmycategories: GetcategoriesService) { }
ngOnInit() {
this.data = this.getmycategories.categories;
console.log(this.getmycategories.categories);
console.log(this.data);
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule,
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
I have been trying to log the data on the console but it returns undefined, APIs are working fine and it's a simple .json collection without any parameter so please advise me if I am missing something and how I can fix it.
Solution
Please refer to the Angular tutorial. The data can not be printed, as the HTTP call might not have finished yet.
To fix your issue I would recommend using Observables
instead of Promises
.
Service
constructor(private http: HttpClient) {}
getservices() {
const url = 'url goes here';
return this.http.get(url);
}
Page
ngOnInit() {
this.getmycategories.getservices().subscribe(response => {
console.log(response);
});
}
Answered By - Marek W
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.