![](/img/trans.png)
[英]How to pass data between components, if they are not parent-child components in 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.