Answer the question
In order to leave comments, you need to log in
How to write asynchronous js functions in html?
Hello!
As you know, there are several ways to work with asynchronous functions in js. For example, Angular is built on the rxjs library, which uses the Observable pattern with its .subscribe. Also in js, in one of the latest specifications, the async / await syntax, based on promises, appeared. And I like to write that way. More succinctly.
For example, we write an api call like this:
public async getUserRoles(userId: string) {
return this.get<number[]>('GetRoles?userId=' + userId).toPromise();
}
this.userRoles = await this.service.getUserRoles(this.userId);
export class UsersApiService extends BaseApiService {
private storage: UserProfileModel[] = null;
constructor(public http: HttpClient) {
super('Users', http);
}
public async GetProfiles() {
if (!this.storage) {
this.storage = (await this.get<any[]>('GetProfiles').toPromise()).map(x => new UserProfileModel(x));
}
return this.storage;
}
public async getUser(userId: string) {
const profiles = await this.GetProfiles();
return profiles.find(x => x.id == userId);
}
public async getUserRoles(userId: string) {
return this.get<number[]>('GetRoles?userId=' + userId).toPromise();
}
public async setUserRoles(userId: string, roles: number[]) {
return this.post('SetRoles', { userId: userId, roles: roles }).toPromise();
}
}
/** Пользователь */
export class UserProfileModel {
/** GUID */
public id: string;
/** Логин */
public userName: string;
/** Эмейл */
public email?: string;
/** Телефон */
public phone?: string;
constructor(obj: any = {}) {
this.id = obj.id;
this.email = obj.email;
this.phone = obj.phone;
this.userName = obj.userName;
}
get shortName(): string {
return this.userName || this.email || this.phone;
}
}
<tr *ngFor="let el of dataSource">
<td class="col">
{{users.getUser(el.assignee).shortName | async}}
</td>
<td class="col">{{el.reporter}}
</td>
<td class="col">{{el.summary}}</td>
<td class="col">{{el.description}}</td>
<td>
<a [routerLink]='["/issue/edit", el.id]'>
<input type="submit" value="Edit" class="btn btn-primary">
</a>
</td>
</tr>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question