简体   繁体   English

使用服务提供程序(打字稿/角度 2)在 ionic 2 视图中恢复和显示 json 数据(对象、数组)

[英]recover and display json data (Object, array) in ionic 2 view using service provider (typescript/angular 2)

I am new with angular 2 and ionic 2 (nodejs and typescript too to be honest).我是 angular 2 和 ionic 2 的新手(老实说,nodejs 和 typescript 也是如此)。

I have a list of users here .这里有一个用户列表。 This is just for a test but later I call a real API to recover my user in database.这只是为了测试,但后来我调用了一个真正的 API 来恢复我的数据库中的用户。

So I create a provider in my ionic 2 project named test-service.ts (here's the code):所以我在我的 ionic 2 项目中创建了一个名为test-service.ts (这是代码):

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PeopleService {

  public users: any[];

  constructor(public http: Http) {
    this.users;
  }

  load(){
    this.http.get('https://demo6000522.mockable.io/test')
    .map(res => res.json())
    .subscribe(
      data => {
        this.users = data;
        console.log(this.users);
        return Promise.resolve(this.users)
      },
      err => {
          console.log("it's seems like there is no users here !");
      }
    );
  }
}

Here I recover my users in the peoples array (check the url above).在这里,我在 peoples 数组中恢复我的用户(检查上面的 url)。

In my users.ts I have this:在我的users.ts我有这个:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
// import our provider here
import {PeopleService} from '../../providers/test-service';

@Component({
  selector: 'page-users',
  templateUrl: 'users.html',
  // Import here our service to use api
  providers: [PeopleService]
})
export class UsersPage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public peopleService: PeopleService) {
    this.loadPeople();
  }

  loadPeople(){
    this.peopleService.load()
  }
}

And finally in my users.html :最后在我的users.html

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Users</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let user of users">
      <p>{{ user.fistname }}</p>
      <p>{{ user.lastname }}</p>
      <p>{{ user.email }}</p>
    </ion-item>
  </ion-list>
</ion-content>

All works well, ie no errors occured, I recover my datas in my console browser but not in my ionic view as you can see on the image below:一切正常,即没有发生错误,我在控制台浏览器中恢复了我的数据,但不在我的 ionic 视图中,如下图所示:

在此处输入图片说明

PS: don't care about the WebSocket connection error. PS:不要在意WebSocket连接错误。 I am using docker and I have not resolve this issue yet.我正在使用 docker,但我还没有解决这个问题。 But it's not the purpose of this post.但这不是这篇文章的目的。 Thank you.谢谢你。

How can I display my json data in the view ?如何在视图中显示我的 json 数据?

  1. use peoples property of your response:使用您回复的peoples财产:
this.users = data['peoples'];

--> Currently your users variable will get the returned object instead of only the user-array. --> 当前,您的users变量将获得返回的对象,而不仅仅是用户数组。

  1. use the users variable from your service:使用您服务中的users变量:
<ion-item *ngFor="let user of peopleService.users">

--> currently your template searches a users var inside of your component. --> 当前您的模板在您的组件内搜索users变量。 Cause there isn't a variable like this, it is undefined.因为没有这样的变量,它是未定义的。 And *ngFor with undefined will result in nothing .而带有 undefined 的*ngFor将不会产生nothing结果。 :) :)

UPDATE更新

How you could do it more elegant..你怎么能做得更优雅..

  1. Use a BehaviorSubject :使用BehaviorSubject
public users = new BehaviorSubject<any /* or your class-type */>([] /* initial value */);
  1. keep your BehaviorSubject up to date..保持你的BehaviorSubject是最新的..
public refresh () {
   this.http.get('https://demo6000522.mockable.io/test')
      .map(res => res.json())
      .map(res => res['peoples'])
      .subscribe(
         ppls => this.users.nex(ppls),
         err => {
            console.log("it's seems like there is no users here !");
      });
}

3.1. 3.1. use it inside of your template在模板中使用它

<ion-item *ngFor="let user of peopleService.users | async">

3.2. 3.2. or subscribe to it and keep a local copy inside of your component或者订阅它并在你的组件中保留一个本地副本

private _users: any[];

ngOnInit() {
   this._users = this.peopleService.users.value; // get current value out of our BehaviorSubject
   this.peopleService.users.subscribe(ppls => this._users = ppls); // subscribe to changes !
   this.peopleService.refresh();
}
<ion-item *ngFor="let user of _users">

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

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