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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.