簡體   English   中英

第一次不加載數據

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

我正在開發一個帶有角度的Ionic應用程序。 它有一個帶有php的API。 因此,我有一個返回JSON的服務,事實是,第一次加載頁面時,它不會從JSON加載數據。

服務:

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

我如何加載它:

@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>

您應該在組件而不是服務上返回observable。 這將確保在初始化組件時加載數據。

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

然后在service.ts上進行以下更改。

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

一定要了解服務和組件的目的。 如Angular 文檔所述

理想情況下,組件的工作就是實現用戶體驗,僅此而已。 組件應該提供用於數據綁定的屬性和方法,以便在視圖(由模板呈現)和應用程序邏輯(通常包括模型的某些概念)之間進行中介。

另一方面,應將獲取和保存數據(從HTTP請求中執行)的職責委托給服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM