简体   繁体   中英

Data don't load at the first time

I'm developing an Ionic app with angular. It has an API with php. So, I've a service that returns a JSON, the thing is, that the first time it loads the page, it doesn't load the data from the JSON.

The service:

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

@Injectable({
providedIn: 'root'
})
export class PlayerService {

posts;

baseURL: String;

constructor(public http: HttpClient) {
    this.baseURL = 'http://127.0.0.1:8000/'
}

getPlayers() {    
this.http.get(this.baseURL + 'GetPlayers')
  .subscribe(data => {
    this.posts = data;
  });
return this.posts;
}

How I load it:

@Component({
  selector: 'app-players',
  templateUrl: './players.page.html',
  styleUrls: ['./players.page.scss'],
})
export class PlayersPage implements OnInit {

constructor(private playerService: PlayerService) { }

players = this.playerService.getPlayers();

ngOnInit() {
 }
}

HTML:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>Players</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
 <ion-list>
    <ion-item *ngFor="let p of players">
      <ion-label>
        <h2>{{p.name}}</h2>
        <h3>{{p.mail}}</h3>
      </ion-label>
    </ion-item>
  </ion-list>
</ion-content>

You should be returning the observable on your component, instead of the service. This will ensure the data is loaded upon initialisation of the component.

@Component({
  selector: 'app-players',
  templateUrl: './players.page.html',
  styleUrls: ['./players.page.scss'],
})
export class PlayersPage implements OnInit {

  constructor(private playerService: PlayerService) { }

  ngOnInit() {
    this.playerService.getPlayers().subscribe(data => {
      this.players = data;
    });
  }
}

And on your service.ts, make the following changes.

getPlayers() {    
  return this.http.get(this.baseURL + 'GetPlayers');
}

Do try to understand the purpose of services, and components. As stated on the Angular documentation ,

Ideally, a component's job is to enable the user experience and nothing more. A component should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).

On the other hand, the duty of fetching and saving data (carrying out of HTTP requests) should be delegated to services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM