简体   繁体   English

第一次不加载数据

[英]Data don't load at the first time

I'm developing an Ionic app with angular. 我正在开发一个带有角度的Ionic应用程序。 It has an API with php. 它有一个带有php的API。 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. 因此,我有一个返回JSON的服务,事实是,第一次加载页面时,它不会从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: 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. 您应该在组件而不是服务上返回observable。 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. 然后在service.ts上进行以下更改。

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

Do try to understand the purpose of services, and components. 一定要了解服务和组件的目的。 As stated on the Angular documentation , 如Angular 文档所述

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. 另一方面,应将获取和保存数据(从HTTP请求中执行)的职责委托给服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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