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

时间:2016-04-13 10:30:01

标签: javascript angular

我正在使用两个并行的angular2组件,并尝试在单击组件-1时更新组件-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 并尝试运行此操作时,我都会收到错误消息:

  

&#34;无法读取属性&#39; next&#39;未定义&#34;。

1 个答案:

答案 0 :(得分:0)

中的

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