【问题标题】:Meteor Angular 2 - autobind not working in the tutorialMeteor Angular 2 - 自动绑定在教程中不起作用
【发布时间】:2017-11-12 22:39:46
【问题描述】:

我正在关注 Meteor - Angular2 教程,一切正常。

唯一不起作用的地方是“详细信息视图”与 Angular2 UI 的自动绑定。例如,如果我导航到 Party1 的详细信息视图,则 Party1 的数据会正确加载并在 Angular2 的“详细信息视图”中可见。之后,如果 Party1 的数据发生更改(例如通过 Mongo shell),则此类更改将发送到显示“详细信息视图”的浏览器(通过 WebSockets),但新数据不会显示在视图。

这是PartyDetailsComponent 类的代码。

export class PartyDetailsComponent extends MeteorComponent implements OnInit, CanActivate {
  partyId: string;
  party: Party;

  constructor(private route: ActivatedRoute, private ngZone: NgZone) {
    super();
  }

  ngOnInit() {
  this.route.params
    .map(params => params['partyId'])
    .subscribe(partyId => {
      this.partyId = partyId;
      this.subscribe('party', this.partyId, () => {
        this.party = Parties.findOne(this.partyId);
      }, true);
    });
  }

  saveParty() {
    Parties.update(this.party._id, {
      $set: {
        name: this.party.name,
        description: this.party.description,
        location: this.party.location
      }
    });
  }

  canActivate() {
    const party = Parties.findOne(this.partyId);
    console.log(party);
    return (party && party.owner == Meteor.userId());
  }

}

这里是PartyDetailsComponent的模板

<form *ngIf="party" (submit)="saveParty()">
  <label>Name</label>
  <input type="text" [(ngModel)]="party.name" name="name">
  <label>Description</label>
  <input type="text" [(ngModel)]="party.description" name="description">
  <label>Location</label>
  <input type="text" [(ngModel)]="party.location" name="location">
  <button type="submit">Save</button>
  <a [routerLink]="['/']">Cancel</a>
</form>

提前感谢您的帮助

【问题讨论】:

  • 视图中没有显示什么?如何将它绑定到视图?
  • 我已经用模板代码更新了问题。未显示的是新值。假设 Party1 的位置是摩纳哥,当我加载详细信息视图时,位置显示正确。如果然后我将位置更改为 Monza,那么我会看到 Monza 的新值到达浏览器(通过 WebSockets),但视图不会自动刷新并且位置仍然是 Monaco。谢谢帮助

标签: meteor angular angular-meteor


【解决方案1】:

实际上,我只是通过阅读更多教程找到了我的问题的答案。

只要在订阅代码中适当地添加 Meteo autorun() 方法,一旦底层 Mongo 文档发生更改,我就可以自动更新 UI。

这是有效的代码

ngOnInit() {
    this.route.params
    .map(params => params['partyId'])
    .subscribe(partyId => {
      this.partyId = partyId;
      this.subscribe('party', this.partyId, () => {
        this.autorun(() => {
          this.party = Parties.findOne(this.partyId);
        }, true);
      }, true);
    });
  }

我不完全清楚的是,为什么如果您直接使用 Meteo Mongo 游标(例如通过模板中的 *ngFor)不需要自动运行。

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 1970-01-01
    • 2018-03-13
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2016-07-19
    相关资源
    最近更新 更多