Reputation: 1
I am working on code to get a list on UI but the list is getting loading very slowly. The data comes from .NET Core2 API. What can be the better way of writing this code to avoid delays in list loading?
service.ts
--------------------
public getMyList(): Observable<IMyList[]> {
const headers = new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
return this.http.get(this.url + '/list', { headers }).pipe(
map((result: IMyList[]) => {
if (result && Object.keys(result).length > 0) {
return result;
} else {
return [];
}
})
);
}
component.ts
--------------------
public myList: IMyList[] = [];
public getMyList(): void {
this.service.getMyList().subscribe(
(result: IMyList[]) => { this.myList = result; }
);
}
component.html
----------------------------------------
<tr class="tableRow" *ngFor="let list of myList = index">
<td class="orgCell">{{list.col1}}</td>
<td>{{list.col2}}</td>
<td>
<label [ngClass]="{'cellStatusInUse':list.col5,'cellStatusNotInUse' : !list.col5}"></label>
{{code.col5 === true ? 'In use' : 'Not used'}}
</td>
</tr>
Upvotes: 0
Views: 446
Reputation: 361
map((result: IMyList[]) => {
if (result && Object.keys(result).length > 0) {
return result;
} else {
return [];
}
})
This is wrong map operator usage. Map function passes each source value through a transformation function to get corresponding output values. Read more here
I think your code should look like
service.ts
--------------------
public getMyList() {
const headers = new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
return this.http.get(this.url + '/list', { headers });
}
component.ts
--------------------
public myList: Observable<IMyList[]> = of([]);
public getMyList(): void {
this.myList = this.service.getMyList().pipe(
map(item => { return item; })
);
}
component.html
----------------------------------------
<tr class="tableRow" *ngFor="let list of myList | async; let i = index;">
<td class="orgCell">{{list.col1}}</td>
<td>{{list.col2}}</td>
<td>
<label [ngClass]="{'cellStatusInUse':list.col5,'cellStatusNotInUse' : !list.col5}"></label>
{{code.col5 === true ? 'In use' : 'Not used'}}
</td>
</tr>
Also, you should receive an empty array from the server instead of null or undefined
Upvotes: 1
Reputation: 22
I think the code is simple, it should not cause any problem. The problem is your backend and how to present your code.
Can you check the code on Web API you mentioned above? If the load time is too long, can you do any thing to improve the API performance.
If there are too many data. For example 10.000 rows. You should do the pagination on Web API. And on Front End you can add infinity scrolling feature. It will boost the load time a lot.
Upvotes: 0