Ionic 3 Angular 5 get request from webService

2019-08-24 18:31发布

I'm trying to get data from a local web service but I cannot print the values ​​in the app.

This is my code:

team-data.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
import 'rxjs/add/operator/map';

@Injectable()
export class TeamDataProvider {
  constructor(public http: HttpClient) {
    console.log('Hello TeamDataProvider Provider');
  }

 apiUrl="http://localhost/MyWebService/api/getteams.php";

 private extractData(res: Response) {
    let body = res;
    return body || {};
  }

  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const err = error || '';
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

  getTeams(): Observable<string[]> {
    return this.http.get(this.apiUrl).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

  getRemoteData(){
    this.http.get(this.apiUrl).map(res => res).subscribe(data => {
    console.log(data);
    });
  }

}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TeamDataProvider } from '../providers/team-data/team-data';
import { HttpClientModule } from '@angular/common/http';

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

home.ts:

import { TeamDataProvider } from '../../providers/team-data/team-data';
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController, public navParams: NavParams, public teamDataProvider: TeamDataProvider) {

   this.getTeam();

  }

  teams: string[];
  errorMessage: string;

  getTeam() {
    this.teamDataProvider.getTeams()
       .subscribe(
        teams => this.teams = teams,
         error =>  this.errorMessage = <any>error);
  }

  ionViewDidLoad(){
   this.teamDataProvider.getRemoteData();
  } 
}

home.html:

   <ion-header>
    <ion-navbar>
      <ion-title>
        Team List
      </ion-title>
    </ion-navbar>
  </ion-header>
  <ion-content>
    <h2>Team List</h2>
      <ion-list inset>
        <ion-item *ngFor="let team of teams">
          <p>{{team.id}}</p>
          <p>{{team.name}}</p>
          <p>{{team.number}}</p>
        </ion-item>
      </ion-list>
    </ion-content>

When I run ionic serve -l:

Runtime Error Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

What did I wrong?

1条回答
forever°为你锁心
2楼-- · 2019-08-24 19:08

A few issues visible at glance:

  • In your home.ts AND your provider you declare variables after constructor function. You should do it BEFORE.
  • Also noted your "teams" var is expected to be Array of objects type and it was string[]. Make sure it is not only typed but also has initial value (like empty array) etc
  • Also it is best to use IonViewDidLoad lifecycle hook for getTeams. Use constructor mostly to assign default/initial values to declared vars

import { TeamDataProvider } from '../../providers/team-data/team-data';
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

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

  teams: Array<any> = [];
  errorMessage: string; 
  
  constructor(public navCtrl: NavController, public navParams: NavParams, public teamDataProvider: TeamDataProvider) {
  }

  getTeam() {
    this.teamDataProvider.getTeams()
       .subscribe(
        teams => this.teams = teams,
         error =>  this.errorMessage = <any>error);
  }

  ionViewDidLoad(){
   this.teamDataProvider.getRemoteData();
   this.getTeam();
  } 
}

查看更多
登录 后发表回答