【问题标题】:How to update the page from the service in ionic2?如何从 ionic2 中的服务更新页面?
【发布时间】:2016-12-15 23:08:24
【问题描述】:

我有一个名为“user-data”的服务,它负责在收到请求时获取“用户数据”。

我有一个页面负责显示“用户数据”。页面加载后,获取数据并显示。

我有一个菜单,其中包含一些按钮。点击这些按钮将向“用户数据”服务发送请求并修改数据。当数据被修改时,我希望页面得到有关更改的通知并适应页面。

我做的是

  • 在服务中:发布一个名为“user:change”的事件,并与修改后的数据一起发送
导出类用户数据{ 用户 = []; …… //- 如果数据改变, //- 发布事件 设置用户(用户){ this.users = 用户; this.events.publish('user:change', users); } }
  • 在页面中,订阅捕捉该事件
导出类 UserListPage { 用户 = []; //- 在页面即将显示时订阅 ionViewWillEnter() { this.events.subscribe('user:change', this.updateUsers); } //- 在页面即将显示时订阅 ionViewDidLeave() { this.events.unsubscribe('user:change', this.updateUsers); } //- 更新 更新用户(用户事件数据){ console.log('即将更新'); if (userEventData[0] instanceof Array) { this.users = userEventData[0]; } 控制台.log(this.users); } }

函数 updateUsers 一切正常,除了 this.users 没有分配新值。很奇怪。

有时,当我调试时,我会收到如下错误:“尝试分配给只读属性”

你知道为什么吗?

【问题讨论】:

    标签: angular typescript ionic2 ionic3


    【解决方案1】:

    我可以建议使用 Observables 代替事件吗?即使您可以使用事件完成相同的操作,但由于您使用服务来获取数据,这将是一种更好的方法。在这里你可以看到这个working plunker中的代码。

    所以交流会是:

    Btn / page ---[call the service]---> Service ---[notify other page and send data]---> Page
    

    所以在服务中,你可以创建一个observable,这样其他页面就可以订阅它,并在数据准备好时得到通知。

    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs/Observable';
    
    @Injectable()
    export class UserDataService  { 
    
      private getDataObserver: any;
      public getData: any;
    
      constructor() {
        this.getDataObserver = null;
        this.getData = Observable.create(observer => {
            this.getDataObserver = observer;
        });
      }
    
      public getUserData() {
        // Fake data to send to the page
        let userList = [
          { id: 1, name: 'user01 '},
          { id: 2, name: 'user02 '},
          { id: 3, name: 'user03 '}]
    
        // This simulates an http request
        setTimeout(() => {
          // The next method will notify all the subscribers and will 
          // send the data.
          this.getDataObserver.next(userList);
        }, 1000);
      }
    }    
    

    next(...) 方法将通知所有订阅者(本例中为其他页面)并将数据发送给它。

    然后在另一个页面中,您只需要订阅该 observable 即可在数据可用时收到通知并像这样调用服务:

    import { Component } from "@angular/core";
    import { UserDataService } from 'service.ts';
    
    @Component({
      templateUrl:"home.html"
    })
    export class HomePage {
    
      users: any[];
    
      constructor(private service: UserDataService) {
          // We subscribe to the observable to be notified when
          // the data is ready
            this.service.getData.subscribe((userList) => {
          this.users = userList;
        });
        }
    
      public getData(){
        this.service.getUserData();
      }
    }
    

    确保在 App 组件的 providers 数组中添加 UserDataService,以便在整个应用程序(单例服务)中使用相同的实例。

    import { Component } from "@angular/core";
    import { ionicBootstrap, Platform } from 'ionic-angular/index';
    import { HomePage } from './home.ts';
    import { UserDataService } from 'service.ts';
    
    @Component({
      template: '<ion-nav [root]="rootPage"></ion-nav>',
      providers: [UserDataService]
    })
    export class MyApp {
      constructor(private platform: Platform) {
        this.rootPage = HomePage;
      }
    }
    
    ionicBootstrap(MyApp);
    

    【讨论】:

    • 感谢您告诉我这种方法。很有用。
    • 很高兴我能帮上忙 :)
    【解决方案2】:

    我唯一错的是在单独的地方编写处理“updateUser”的函数。以下代码适用于我:

    <pre>
    export class UserListPage {
        users = [];
    
        //- subscribe when the page is about to show
        ionViewWillEnter() {
            this.events.subscribe('user:change', (userEventData){
                console.log('About to update');
                if (userEventData[0] instanceof Array) {
                      this.users = userEventData[0];
                }
                console.log(this.users);
            );
        }
    
        //- subscribe when the page is about to leave
        ionViewDidLeave() {
            this.events.unsubscribe('user:change', ()=>());
        }
    
    }
    </pre>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多