如何在Angular2-Meteor中使注入服务具有反应性

时间:2016-09-06 17:28:11

标签: meteor angular angular2-meteor

我是Angular2的新手,我正在尝试使用自定义组件来管理Mongo.Collection对象的注册表。我的问题是,当集合加载时,我似乎无法让Angular刷新UI。

如果您查看下面的代码,您会看到有一个注入了DatasetService的Component。此服务管理集合的注册表。我猜这个问题与Meteor.autorun()方法将处理从Angular'区域'&中取出的事实有关。我需要以某种方式将进程重新注入Angular zone / digest?

客户和客户服务器:

export const Meetings = new Mongo.Collection<any>('meetings');

仅限服务器

Meteor.publish('meetings', function(options: any) {
  return Meetings.find({});
});

仅限客户

class Dataset {
  cursor: Mongo.Cursor<any>;
  loading: boolean = true;

  constructor( public collection: Mongo.Collection<any> ) {
    Tracker.autorun(() => {
      this.loading = true;
      Meteor.subscribe('meetings', {}, () => {
        this.cursor = this.collection.find({});
        this.loading = false;
      });
    });
  }
}

@Injectable()
class DatasetService {
  datasets: Dataset[] = [];

  register( id: string, collection: Mongo.Collection<any> ) : Dataset {
    return this.datasets[id] = new Dataset( collection, options );
  }
}

@Component({
  selector: 'meetings-list',
  template: `<ul><li *ngFor="let meeting of meetings.cursor">{{meeting.name}}</li></ul>`,
  viewProviders: [DatasetService]
})
class MeetingsListComponent extends MeteorComponent implements OnInit {
  meetings: Dataset;

  constructor(private datasetService: DatasetService) {
    super();
  }

  ngOnInit() {
    this.meetings = this.datasetService.register( 'meetings', Meetings );
  }

  checkState() {
    console.log(this.loading);
  }
}

如果我加载页面,则不会显示会议列表。但是,如果我通过单击按钮手动调用'checkState()',则刷新UI&amp;举行会议。

任何帮助,清晰度或实现我想要做的事情的替代方法都将非常感激!

1 个答案:

答案 0 :(得分:1)

你是对的。触发更改的代码从Angular2区域外部进入,因此您需要将其推入区域以执行更改。为此,您需要将NgZone注入您的服务。然后,您可能需要将其传递给Dataset实例,因为这是应该触发更新的代码所在的位置。例如,这可能有效:

import { Injectable, NgZone, Inject } from '@angular/core';

class Dataset {
  cursor: Mongo.Cursor<any>;
  loading: boolean = true;

  constructor( public collection: Mongo.Collection<any>, zone: NgZone ) {
    Tracker.autorun(() => {
      this.loading = true;
      Meteor.subscribe('meetings', {}, () => {
        zone.run(() => {  //<-- new line
          this.cursor = this.collection.find({});
          this.loading = false;
        });               //<-- end of new line
      });
    });
   }
}

@Injectable()
class DatasetService {
  datasets: Dataset[] = [];
  private zone: NgZone;

  // Inject Here
  constructor(@Inject(NgZone)zone: NgZone) { this.zone = zone; }

  register( id: string, collection: Mongo.Collection<any> ) : Dataset {
    //Add zone to Dataset constructor, 
    // not sure before or after options (not sure where options comes from or goes
    return this.datasets[id] = new Dataset( collection, this.zone, options );
  }
}