尝试使用REST服务时,离子屏幕变为空白

时间:2018-05-10 11:50:44

标签: angular rest ionic-framework ionic3

我目前正在尝试在Ionic中使用RESTful服务。

我在需要它的页面上导入了REST服务,还有从数据库中检索用户的方法。

然而,在我输入并保存方法并导入所有方法后,我的离子实验室移动屏幕显示为空白。我试图撤消所有代码,但移动屏幕仍为空白。

我可以知道为什么吗?

我的app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpClientModule } from '@angular/common/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { RestProvider } from '../providers/rest/rest';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    RestProvider
  ]
})
export class AppModule {}

我的REST提供商rest.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class RestProvider {

  apiUrl = '';

  constructor(public http: HttpClient) {
    console.log('Hello RestProvider Provider');
  }

  getUsers() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/users').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}

}

我的主页home.ts

import { Component } from '@angular/core';
import { NavController, NavParams, MenuController, AlertController } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage{

  users: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public menuCtrl: MenuController, public alertCtrl: AlertController, public restProvider: RestProvider) {
      this.getUsers();
  }

  getUsers() {
    this.restProvider.getUsers()
    .then(data => {
      this.users = data;
      console.log(this.users);
    });
  }

  ionViewWillEnter() {

       this.menuCtrl.swipeEnable( false )
   }

   ionViewDidLeave() {

       this.menuCtrl.swipeEnable( true )
   }

}

2 个答案:

答案 0 :(得分:0)

使用rxjs中的toPromise方法:

import 'rxjs/add/operator/toPromise';

getUsers() {
    return this.http.get(this.apiUrl+'/users')
      .toPromise()
      .then(data => data.json())
      .catch(err => console.log(err))
  }

答案 1 :(得分:0)

结果证明,使用Visual Studio的模拟器会导致此问题。使用外部仿真器(例如您自己的设备)不会导致此类问题。