Reputation: 237
I have a service and when I run the code labeled #1 it returns to data in the console but when I assign it to a variable I get undefined.
Here is the code:
In the Service:
executeShell(command) {
exec(command, (error, stdout, stderr) => {
if (error) {
return stderr;
} else {
return stdout;
}
});
}
In the component.ts:
output: any; // define the variable
Then if I run #1 below:
this.electronService.executeShell('ls'); // #1
the output on the console is corrent.
But If I try this:
this.output = this.electronService.executeShell('ls'); // #2
console.log(this.output); // #2
I get undefined
My issue is that #1 returns the list in the console but #2 is returning undefined.
How can I fix this?
Upvotes: 0
Views: 142
Reputation: 31125
The value is returned from a callback, so it's asynchronous. You might have to return an observable/promise to capture the data. Try the following
Service
executeShell(command) {
let result = new BehaviorSubject<any>(null);
exec(command, (error, stdout, stderr) => {
if (error) {
result.error(stderr);
} else {
result.next(stdout);
}
});
return result.asObservable();
}
Now subscribe in the component to get the notification.
Component
this.electronService.executeShell('ls').subscribe(
response => {
if(response) { // <-- default value of the observable is `null`
this.output = response;
}
},
error => {
this.output = error;
}
);
Upvotes: 1