繁体   English   中英

如何在angular2中组件之间的事件上更新数据?

[英]How to update data on event between components in angular2?

我正在使用两个并行angular2组件,并尝试在单击component-1时更新component-2中的数据。

这是代码:

共享服务:

class updateData {
  constructor (){
    this._req = {};
    this.observer;
    this.updateReq = new Rx.Observable(function (observer) {
              return this.observer = observer;
    }).share();
  }
  update(req) {
    this._req = req;
    this.observer.next(req);
  }
};

组件1:

app.getLogs = ng.core.Component({
    selector: 'get-logs',
    providers: [updateData, ng.http.HTTP_PROVIDERS, httpService],
    template: "<button class='btn btn-success pull-left mrT2' (click)='getLogfilters()' >Get Logs</button>"
  })

  .Class({
    constructor: [updateData,ng.http.Http, httpService, function (updateData, http, service){
      this.result = {};
      this.http = http;
      this.service = service;
      this.updateData = updateData;
      this.reqBody = {};
    }],

    getLogfilters: function(){
      var fed = (function(){
        return this;
      }).bind(this);

      setTimeout(function(){
        var self = fed();
        self.service.getLogs(req, selectedCompany).subscribe(function(result){
          this.result = JSON.parse(result._body);

          //--------- UPDATE DATA HERE--------------//
          self.updateData.update(req);

        }.bind(this), function(error){
          error = JSON.parse(error._body);
          console.log(error.code, error.message);
        });

      });
    }
  });

组件2:

app.AuditLogs =
    ng.core.Component({
      selector: 'audit-logs',
      providers: [updateData, ng.http.HTTP_PROVIDERS, httpService],
      templateUrl: '/public/webapp/ng2/audit_logs/audit-logs.html',
    })
    .Class({
      constructor:[updateData,ng.http.Http, httpService, function(updateData, http, service) {
        this.result = {};
        this.http = http;
        this.logs = [];
        this.updateData = updateData;

        // --------- CATCH UPDATED DATA HERE ---------- //
        this.updateData.updateReq.subscribe(function (req) { 
           console.log(req);
        });
      }]
  });

每当我单击组件2并尝试运行它时,都会出现错误:

“无法读取未定义的属性'next'”。

this

this.updateReq = new Rx.Observable(function (observer) {
          return this.observer = observer;
}).share();

不是您所期望的,因为

`function (observer)` in

要么将其更改为

(observer) => 

或者

this.updateReq = new Rx.Observable(function (observer) {
          return this.observer = observer;
}.bind(this)).share();

另请参阅https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

暂无
暂无

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

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