我有一个服务,当我运行标记为 #1 的代码时,它会返回到控制台中的数据,但是当我将其分配给变量时,我变得未定义。
这是代码:
在服务中:
executeShell(command) {
exec(command, (error, stdout, stderr) => {
if (error) {
return stderr;
} else {
return stdout;
}
});
}
在组件.ts中:
output: any; // define the variable
然后,如果我在下面运行#1:
this.electronService.executeShell('ls'); // #1
控制台上的输出是相关的。
但是如果我尝试这个:
this.output = this.electronService.executeShell('ls'); // #2
console.log(this.output); // #2
我被取消定义
我的问题是 #1 在控制台中返回列表,但 #2 返回未定义。
我该如何解决这个问题?
该值是从回调返回的,因此它是异步的。您可能需要返回可观察量/承诺才能捕获数据。尝试以下操作
服务
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();
}
现在订阅组件以获取通知。
元件
this.electronService.executeShell('ls').subscribe(
response => {
if(response) { // <-- default value of the observable is `null`
this.output = response;
}
},
error => {
this.output = error;
}
);