Reputation: 695
I want to create a simple app that fetches some user data from a get request. I have followed several tutorials and nothing seems to work for me. First, I have created a service like this, called profile.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ProfileService {
url = 'https://example.com/api/user';
constructor(private http: HttpClient) { }
getProfile(id: string) {
return this.http.get(`${this.url}/${id}`);
}
}
Also, in the app.module.ts, I have imported HttpClientModule, like this:
import { 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 {}
Then, on one of my tabs, called tab1.module.ts (I use tabs module), I do the following:
import { IonicModule } from '@ionic/angular';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { NgModule, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Tab1Page } from './tab1.page';
import { ProfileService } from '../profile.service';
@NgModule({
imports: [
IonicModule,
CommonModule,
FormsModule,
RouterModule.forChild([{ path: '', component: Tab1Page }])
],
declarations: [Tab1Page]
})
export class Tab1PageModule implements OnInit {
accountData = null;
constructor(private profileService: ProfileService) { }
ngOnInit() {
console.log('test')
this.profileService.getProfile('3')
.subscribe(result => {
console.log('my data:', result)
this.accountData = result
});
}
}
Finally, I try to print the results in the tab1.page.html :
<ion-content>
<ion-list>
<ion-item>
<ion-icon slot="start" color="primary" name="male"></ion-icon>
<ion-label>{{ accountData?.name }}</ion-label>
</ion-item>
</ion-list>
</ion-content>
And nothing is printed. Note that it does not work even if I do not use implements OnInit in my Tab1PageModule. Nothing gets printed in the console either. Is there something wrong because I use the tabs module? Ideally, in the end, I want a different function from profile service to be called for each tab. I use Ionic 5.
Upvotes: 0
Views: 158
Reputation: 164
I tried to reproduce your case, for me it worked. For me it looks like you mixed up the tab1.module.ts with tab1.page.ts . The Module is only there to import your packages and lazy load your whole module. It has a different duty then the tab1.page.ts which has a binding to it's .html counterpart. I prepared a Project which worked for me. Checkout especially profile.service.ts, app.module.ts, tab1.module.ts and tab1.page.ts.
I basically took the code and put it into the tab1.page.ts and removed unecessarities.
Upvotes: 1