0

Good morning!

I have the following Angular/TypeScript service, but the query portion of the function happens asynchronously so the return statement is executed before the data is retrieved from the server. Is there a way to add async/await to this function so it waits for the data to be assigned to the Users variable before executing the return statement?

    interface IUserService {
        getAll(): entities.IUser[];
    }

    export class UserService implements IUserService {
        static $inject: string[] = ['dataAccessService'];
        constructor(private dataAccessService: dataAccess.DataAccessService<entities.IUser>) {

        }

        getAll(): app.domain.entities.IUser[] {
            var users: app.domain.entities.IUser[];
            var userResource = this.dataAccessService.getDataResource('https://api.github.com/users');
            userResource.query((data: app.domain.entities.IUser[]) => {
                users = data;
            });

            return users;
        }
    }

    angular
        .module('domain')
        .service('userService',
                    UserService);
BSmith
  • 123
  • 8
  • Have you seen this?: http://stackoverflow.com/questions/32401741/async-await-simple-example-typescript – mentat Oct 26 '15 at 02:36
  • Interesting... Thanks! If I am using modules, how can I get them to nest that async keyword into each IFFE layer of the namespace. I may have to find a work-around until TypeScript 2.0. – BSmith Oct 26 '15 at 17:11

1 Answers1

0

With $resource, you can actually set the resource values directly to a variable rather than setting the variable in the callback method.

interface IUserService {
    getAll(): ng.resource.IResourceArray<ng.resource.IResource<IUser>>;
}

export class UserService implements IUserService {
    static $inject: string[] = ['dataAccessService'];
    constructor(private dataAccessService: dataAccess.DataAccessService<entities.IUser>) {
        var userResource = this.dataAccessService.getDataResource('https://api.github.com/users');
    }

    getAll(): ng.resource.IResourceArray<ng.resource.IResource<IUser>> {
        return userResource.query();
    }
}

angular
    .module('domain')
    .service('userService',
                UserService);

Then in my controller I can set the values directly to my variable to render in my view.

class UserController {
    user: ng.resource.IResourceArray<ng.resource.IResource<IUser>>;

    static $inject: string[] = ['UserService'];
    contructor(private userService: IUserService) {

    }

    this.users = this.userService.GetAll();
}

angular.module('app').controller('UserController', UserController);

This will give me access to my user properties as well as some additional properties like the original promise so I can add additional functionality if I would like to.

Hope that helps anyone with a similar issue.

BSmith
  • 123
  • 8