我想做什么:
我希望在对象列表上设置多个订阅,以便在请求的答案完成时动态更新对象。
问题:
目前的问题是,在for循环中,每个元素都会用订阅覆盖前一个项目,所以每次只获得所有对象的最后一个订阅。
实际代码:
const myObject = {
a: {
b: {
c: {
d: 'test'
}
}
},
c: {
d: 'Test 2'
}
},
isObject = obj => obj && typeof obj === 'object',
hasKey = (obj, key) => key in obj;
function nestedObj(obj, property, callback) {
return property.split('.').reduce((item, key) => {
if (isObject(item) && hasKey(item, key)) {
return item[key];
}
return typeof callback != undefined ? callback : undefined;
}, obj);
}
console.log(nestedObj(myObject, 'a.b.c.d')); //return test
console.log(nestedObj(myObject, 'a.b.c.d.e')); //return undefined
console.log(nestedObj(myObject, 'c.d')); //return Test 2
console.log(nestedObj(myObject, 'd.d', false)); //return false
console.log(nestedObj(myObject, 'a.b')); //return {"c": {"d": "test"}}
在服务中我做的事情是这样的:
// data list with hosts
let list = [
{
"name": "joe",
"hosts": [
{
"name": "vlm01",
"status": null,
"update": null
}
]
},
{
"name": "foo",
"hosts": [
{
"name": "vlm02",
"status": null,
"update": null
}
]
},
{
"name": "bar",
"hosts": [
{
"name": "vlm03",
"status": null,
"update": null
}
]
}
]
// for loops to set a subscriber for each host
list.forEach(item => {
for (let i = 0; i < item.hosts.length; i++) {
this.statusHostService.getHostStatus().subscribe(result => item.hosts[i].status = result);
this.statusHostService.getHostUpdateStatus().subscribe(result => item.hosts[i].update = result);
this.hostService.startDeployment(host.name);
};
});
在我的HTML代码中,我有一个状态视图,它正在观看订阅的结果。 您是否知道如何以正确的Angular方式执行此操作&#34;?
通过创建新的服务实例解决方案
private hostStatusSubject = new BehaviorSubject<string>('');
private hostStatusUpdateSubject = new BehaviorSubject<boolean>(null);
public getHostStatus() {
return this.hostStatusSubject;
}
public getHostUpdateStatus() {
return this.hostStatusUpdateSubject;
}
public startDeployment() {
// load some config data then trigger the calls with the correct params
this.loadHostStatus(url1, param1);
this.loadHostStatusUpdate(url2, param2);
}
private loadHostStatus(url, param) {
// load data over rest api
this.hostStatusSubject.next(response);
}
private loadHostStatusUpdate(url, param) {
// load data over rest api
this.hostStatusUpdateSubject.next(response);
}
但我也会尝试使用forkJoin的解决方案。 当我有时间时,我会整合并测试它。