TypeError: instances.map is not a function angular loopback

1k Views Asked by At

I'm using the @mean-expert/loopback-sdk-builder to generate my api on angular 4.3.6 and i am getting an error when i use this call

this._userApi.findUsersByRoles([{'name':'cliente'}]).subscribe((users: User[]) => {
  this.users = users;
}, (err) => {console.log(err) })

When i try this method in the loopback explorer i am getting an array of users.

debug capture

This is the 'findUsersByRoles' function generated by the loopback sdk

  public findUsersByRoles(roles: any, customHeaders?: Function): Observable<User[]> {
    let _method: string = "GET";
    let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
    "/users/findUserByRoles";
    let _routeParams: any = {};
    let _postBody: any = {};
    let _urlParams: any = {};
    if (typeof roles !== 'undefined' && roles !== null) _urlParams.roles = roles;
    let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
    return result.map((instances: Array<User>) =>
        instances.map((instance: User) => new User(instance))
    );
  }

And this is the printed error in the console :

Capture link

I suspect that this could be a bug in the sdk builder, since the angular project is recent and has not had many changes in the overall structure.

Solution

As I have been told in the answers, the problem is that instances is not an array, to fix this i had to set the property root : true on the remoteMethod definition in the loopback model

returns: {
        arg: 'users',
        type: 'array',
        root : true
      }
2

There are 2 best solutions below

0
On BEST ANSWER

instances is an object, as you see in the debug capture. It has the property users which is an array. So you need to call the map function on the users array.

instances.users.map((instance: User) => new User(instance));
2
On

The reason for the error is that you are calling map on the variable which is not an array, make sure to console log instances variable to see if it really contains an array.The error is telling you that map is not a function because your variable is not any array and map is array function in this context.