Reputation: 39
I have function1(), when I am calling function1 response.hasOwnProperty('xxx') always come false
function1() {
let value1 = this.findTreeByNode({ nodeUuid: this.cart.selectedNodeUuid })
...... HERE I NEED THE VALUE OF value1 returned by findTreeByNode() ......
}
}
this is findTreeByNode() function which calls backend
findTreeByNode(node: any, isSearch: boolean = false) {
return this.treeService.getParentList(node).subscribe(res => {
this.topNodes.forEach((topNodes, treeIndex) => {
if (res.data.length > 0) {
if (topNodes.nodeUuid === res.data[0].nodeUuid) {
res.treeIndex = treeIndex;
}
}
});
return res;
});
}
The issue is **function1 () ** always execute before response come from inside backend call function. Both functions are in the same component. nested function of function1 has beckend call and subscribe to a observable. I have tried to make function findTreeByNode () return observable so I can subscible function1, but not working. i want to execute "let response = ...." only execute after function return something.
Upvotes: 1
Views: 44
Reputation: 1771
I would cut the subscription out of your findTreeByNode function. This allows you to handle your object that you get back from your subscription after you actually get the response. Using your example, something similar to below:
function1() {
if (!this.cart.entitlementsObj.ekey_view_tree) {
this.treeService.getParentList({ nodeUuid: this.cart.selectedNodeUuid }).subscribe(
(res: any) => {
const response = this.findTreeByNode(res);
if (response.hasOwnProperty('treeIndex')) {
this.componentRef[response.treeIndex].instance.hideTree();
}
}
);
}
}
findTreeByNode(res: any, isSearch: boolean = false) : any {
res.treeIndex = 0;
this.topNodes.forEach((topNodes, treeIndex) => {
if (res.data.length > 0) {
if (topNodes.nodeUuid === res.data[0].nodeUuid) {
res.treeIndex = treeIndex;
}
}
});
return res;
}
Upvotes: 1