0

Below is a snippet of code that calls a Loopback API method with an array of values. The input values are correct, no errors are thrown on the API and the subscribe block runs as expected.

    const newStudentGroups =
            selectedStudentIds.map(sId => ({
                studentId: sId,
                groupId: this.group.id,
                schoolId: this.curSchool.id,
                programId: this.curProg.id,
            }));
   this.stuGroupApi.create(newStudentGroups)
       .subscribe((newStu) => {
          console.log(newStu.map(s=>s[0]));
       });

However the values returned to the subscribe block as newStu appears as an object of the form:

{ 
  0:{
     studentId: 123,
     groupId: 321,  
     schoolId: 1,
     programId: 5
    },
  1:{
     studentId: 132,
     groupId: 322,  
     schoolId: 1,
     programId: 5
    },
  2:{studentId: 143,
     groupId: 331,  
     schoolId: 1,
     programId: 5
    }
}

I need an array of StudentGroup objects the same as I put in. I recognize that I can forkJoin individual calls to the API but that seems like a lot of network traffic vs a single call that could/should run as a batch on the DB.

I can't find much to suggest if I've done this wrong or if there's a canonical way to get this back into the form in which I sent it. Is this a bug? Am I running the call incorrectly?

EDIT: I've been inspecting the actual network requests and it looks like Loopback is actually returning the array as required. So this has to be the SDK on my end somewhere. Does @mean-expert/loopback-sdk-builder convert arrays to objects intentionally or did I misconfigure something? I'm on version"@mean-expert/loopback-sdk-builder": "^2.1.0-rc.10.5".

4

1 回答 1

0

更新的答案

TL;DR 使用createMany函数而不是create.

鉴于@mean-expert/loopback-sdk-builder 解析 BaseLoopBackApi 中的响应(它应该在 中services/core),调用该create方法将尝试将响应解析回服务的通用数据类型(可能是 StudentGroup 来调用?) . 但是,默认情况下,此解析将使用Object.assign(this, data);. 不幸的是,这将按照您显示的方式将数组转换为对象。

例如

Object.assign({}, ['hi', 'there'])

将产生

{ '0': 'hi', '1': 'there' }

但是,@mean-expert/loopback-sdk-builder 提供了另一个默认功能来为您解决该问题。只需将您的呼叫改为使用即可createMany

因此:

const newStudentGroups = selectedStudentIds.map(sId => ({
    studentId: sId,
    groupId: this.group.id,
    schoolId: this.curSchool.id,
    programId: this.curProg.id,
}));
this.stuGroupApi.createMany(newStudentGroups)
   .subscribe(newStus => {
      console.log(newStus);
   });

原始答案

给定来自服务器的响应,您可以通过运行来获取可用的数组

this.stuGroupApi.create(newStudentGroups)
   .map(newStu => Object.keys(newStu).map(i => newStu[i]))
   .subscribe((newStu) => {
      console.log(newStu.map(s=>s[0]));
   });
于 2018-06-22T18:22:05.077 回答