javascript - Angular - 从 'then' 内部返回值

标签 javascript angular typescript promise

我在 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/

相关文章:

javascript - Google App 引擎 Nodejs Puppeteer 中的全局变量

javascript - 对复杂数据元素的引用

TypeScript:错误 TS2322:类型 '{}' 无法分配给类型 '...'

reactjs - 使用 Jest/Enzyme 延迟后测试 React 组件的意外行为

javascript - 从 YT API JSON 获取 YouTube 横幅

Javascript:如何使用数组给定的对象名称动态创建嵌套对象

javascript - 图例分页

angular - NullInjectorError:Angular 2中没有InjectionToken LOCAL_STORAGE的提供程序

javascript - Angular 2 : Class Properties Not Updating On params retrieval

尝试绑定(bind)到字符串常量时,Angular2 @Input undefined