我在 StackOverflow 上看过类似的问题,但没有一个符合我的具体问题:
我在 Angular 6 服务中有一个 TypeScript 函数,像这样调用另一个服务中的函数:
服务 1:
myArray: Array<IMyInterface>
...
getArray(): Observable<IMyInterface[]> {
this.myArray= this.service2.getAnArray(1);
return Observable.of(this.myArray);
}
服务2
getAnArray(myEntityId): Array<IMyInterface> {
const myArray2: IMyInterface[] = [];
this.getConnection().then(connection => {
connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
someJson.forEach( x => myArray2.push(x));
return myArray2;
})
});
}
它给了我 Service2 中的错误 声明类型既不是“void”也不是“any”的函数必须返回一个值。
我需要返回 myArray2
after connection.invoke('GetEntityById', myId)
已解决,因为数组仅在之后填充解决了,这就是为什么我尝试在 then
中执行此操作。
我该怎么做?
最佳答案
这可能/可能不适合您的需求,但您可以从您的服务方法中返回 Promise
,例如:
getAnArray(myEntityId) {
const myArray: IMyInterface[] = [];
// Note the return here
return this.getConnection().then(connection => {
return connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
someJson.forEach( x => myArray.push(x));
return myArray;
})
});
}
你的调用代码看起来像
getAnArray(someId).then(function(theArray) {. . .});
关于javascript - Angular - 从 'then' 内部返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049882/