我在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;
})
});
}
它给了我服务2中的错误A function whose declared type is neither 'void' nor 'any' must return a value.
我需要在connection.invoke('GetEntityById', myId)
解析后返回myArray2
,因为数组仅在解析后填充,这就是我尝试在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) {. . .});
这有点晚了。但有人可能会发现这很有帮助。 你可以为此使用Async/Await。原因是每次发生"等待"时,它都会保留线程,直到作业完成。
async getAnArray(myEntityId) {
await this.getConnection();
try {
let result = await connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
someJson.forEach(x => myArray.push(x));
return myArray;
})
} catch (err) {
console.log(err);
}
}
要获得结果(将返回承诺(,请执行以下操作:
this.getAnArray(myEntityId).then((data) => {
console.log('data' , data);
});