Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用服务通信时触发更改检测_Javascript_Angular_Components_Angular2 Observables_Angular2 Changedetection - Fatal编程技术网

Javascript 使用服务通信时触发更改检测

Javascript 使用服务通信时触发更改检测,javascript,angular,components,angular2-observables,angular2-changedetection,Javascript,Angular,Components,Angular2 Observables,Angular2 Changedetection,所以我有两个不相关的组件,我试图使用服务和行为主体在它们之间进行通信。一切都很酷,数据是交换的,但是当我从一个组件调用服务时,它不会触发另一个组件上的更改检测 因此,为了展示我在代码中所说的内容: 服务: 从'@angular/core'导入{Injectable,Optional,EventEmitter}; 从'@angular/Http'导入{Http}; 导入'rxjs/add/operator/map'; 从'rxjs/BehaviorSubject'导入{BehaviorSubje

所以我有两个不相关的组件,我试图使用服务和行为主体在它们之间进行通信。一切都很酷,数据是交换的,但是当我从一个组件调用服务时,它不会触发另一个组件上的更改检测

因此,为了展示我在代码中所说的内容:

服务:

从'@angular/core'导入{Injectable,Optional,EventEmitter};
从'@angular/Http'导入{Http};
导入'rxjs/add/operator/map';
从'rxjs/BehaviorSubject'导入{BehaviorSubject};
从'@angular/router/src/utils/collection'导入{forEach};
@可注射()
导出类SbkService{
项目:任何=[];
private _itemsSource=新行为主体(0);
items$=此。_itemsSource.asObservable();
建造师(
private\u localStorageService:localStorageService
) {}
商店选择(项目){
此.items.push(item);
这是setLocalStorage();
}
removeSelection(selectionId){
对于(var i=this.items.length-1;i>=0;i--){
if(this.items[i].selectionId==selectionId)
本条第1条拼接(i,1);
}
这是setLocalStorage();
返回true;
}
getLocalStorage(){
this.items=this.\u localStorageService.get('items');
this._itemsSource.next(this.items);
归还此物品;
}
setLocalStorage(){
this.\u localStorageService.set('items',this.items);
this._itemsSource.next(this.items);
返回true;
}

}
如果我没有错,你应该通过你的行为主体设置你观察到的“项目”的下一个“序列”

你能修改并尝试一下吗

storeSelection(item){
   const itemsAux = this._itemsSource.getValues();
   itemsAux.push(item);
   this._itemsSource.next(itemsAux);
}

setLocalStorage(){
   this._localStorageService('items', this._itemsSource.getValues();
   return true;
}

排序列表在哪里?谢谢你的回答,但这似乎没有改变任何事情。现在我强制使用CDR进行更改检测。我在datatable组件上也遇到了同样的问题。我用数组上的切片函数解决了它,每次我改变数组。。。无论您在何处编写此.items.push(项目),在将其设置为主题“next”之前,您都可以执行此操作.items.push(项目);设aux=this.items.slice();本._项目来源下一步(辅助);另一个选项是,您可以在onInit()中尝试异步管道而不是订阅服务器,如下所示:模板: