Angular 6-如何在不执行服务功能的情况下将其指向JSON对象

时间:2018-10-27 10:45:47

标签: angular angular6

我已经存储了这样的JSON

to_be_load: {
  type: string;
  status: number;
  message: string;
  online: { fn: Promise<any>; message: string; };
  offline: { fn: Promise<any>; message: string; };
}[];

  this.to_be_load = [
      {
        type: 'floors',
        status: 0,
        message: 'Floors loading',
        online: {
          fn: this.floors.getFromCloud(),
          message: 'Floors loaded from cloud'
        },
        offline: {
          fn: this.floors.getFromLocal(),
          message: 'Floors loaded from local'
        }
      },
      {
        type: 'Categories',
        status: 0,
        message: 'Categories loading',
        online: {
          fn: this.category.getFromCloud(),
          message: 'Categories loaded from cloud'
        },
        offline: {
          fn: this.category.getFromLocal(),
          message: 'Categories loaded from local'
        }
      }]

如果无法从离线执行功能,我的目标是在线执行所有功能

我加载这些数据的功能看起来像这样

private loadData() {
    for (const item of this.to_be_load) {
      item.online.fn.then(() => {
        item.status = 1;
        item.message = item.online.message;
        this.can_move();
      }).catch(() => {
        item.offline.fn.then(() => {
          item.status = 2;
          item.message = item.offline.message;
          this.can_move();
        }).catch(() => {
          item.status = 3;
          item.message = 'Error';
        });
      });
    }
  }

在这里,我的问题是当我将其分配给JSON时函数开始执行,是否有任何可能的方式以角度或打字稿方式来解决此问题,

1 个答案:

答案 0 :(得分:1)

您不是在分配功能,而是在分配功能。应该是这样的:

this.to_be_load = [
  {
    type: 'floors',
    status: 0,
    message: 'Floors loading',
    online: {
      fn: () => this.floors.getFromCloud(),
      message: 'Floors loaded from cloud'
    },
    offline: {
      fn: () => this.floors.getFromLocal(),
      message: 'Floors loaded from local'
    }
  },
  {
    type: 'Categories',
    status: 0,
    message: 'Categories loading',
    online: {
      fn: () => this.category.getFromCloud(),
      message: 'Categories loaded from cloud'
    },
    offline: {
      fn: () => this.category.getFromLocal(),
      message: 'Categories loaded from local'
    }
  }]

然后:

private loadData() {
for (const item of this.to_be_load) {
  item.online.fn().then(() => {
    item.status = 1;
    item.message = item.online.message;
    this.can_move();
  }).catch(() => {
    item.offline.fn().then(() => {
      item.status = 2;
      item.message = item.offline.message;
      this.can_move();
    }).catch(() => {
      item.status = 3;
      item.message = 'Error';
    });
  });
}

换句话说,fn: this.floors.getFromCloud()分配了getFromCloud()函数的结果。尽管此fn: () => this.floors.getFromCloud()定义了一个功能。这样,您以后可以在需要时使用item.online.fn()进行调用。