【问题标题】:ionic http get inside tabs module离子http进入标签模块
【发布时间】:2020-03-01 12:35:44
【问题描述】:

我想创建一个从 get 请求中获取一些用户数据的简单应用。我已经遵循了几个教程,但似乎没有什么对我有用。首先,我创建了一个类似这样的服务,名为 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}`);
  }
}

另外,在app.module.ts中,我导入了HttpClientModule,像这样:

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 {}

然后,在我的一个标签上,称为 tab1.module.ts(我使用标签模块),我执行以下操作:

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
    });
  }

}

最后,我尝试在 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>

并且没有打印任何内容。请注意,即使我在 Tab1PageModule 中不使用 implements OnInit,它也不起作用。控制台中也没有打印任何内容。因为我使用标签模块有什么问题吗?理想情况下,最后,我希望为每个选项卡调用与配置文件服务不同的功能。我使用 Ionic 5。

【问题讨论】:

    标签: angular ionic-framework ionic4


    【解决方案1】:

    我试图重现你的情况,对我来说它有效。对我来说,您似乎将 tab1.module.ts 与 tab1.page.ts 混淆了。该模块仅用于导入您的包并延迟加载您的整个模块。它的职责与 tab1.page.ts 的职责不同,tab1.page.ts 绑定到它的 .html 对应项。我准备了一个对我有用的项目。 Checkout 尤其是 profile.service.ts、app.module.ts、tab1.module.ts 和 tab1.page.ts。

    The Stackblitz project

    我基本上把代码拿来放到tab1.page.ts中,去掉了不必要的东西。

    【讨论】:

    • 非常感谢,成功了!我在 tab1.page.ts 中添加了相同的代码块,它起作用了。
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2019-10-08
    • 2015-05-09
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多