简体   繁体   中英

Angular http request is delayed. How can I speed it up?

When I call HTTP request to api server, the response is delayed.

After displayed empty table, the response is displayed after 2 seconds.

Is there a way to solve this?

Using resolvers may fix, displaying empty table. Here is an example, of how to use resolver

// resolver.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ContactsService } from './contacts.service';

@Injectable()
export class ContactResolve implements Resolve<any> {

  constructor(private contactsService: ContactsService) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.contactsService.getContact(route.params['id']);
  }
}

.

// router.ts
import { Routes } from '@angular/router';
import { ContactsListComponent } from './contacts-list.component';
import { ContactsDetailComponent } from './contacts-detail.component';
import { ContactResolve } from './contact.resolve';

export const AppRoutes: Routes = [
  { path: '', component: ContactsListComponent },
  { 
    path: 'contact/:id',
    component: ContactsDetailComponent,
    resolve: {
      contact: ContactResolve
    }
  }
];

An example with plunker, of how to use resolvers in angular2

Since you are taking data from the server, network flight is supposed to consume some time depending on the speed of your internet connection and how good your backend servers response to your query. Now there some options through which you can make user experience better in your case.

  • You can show a loading icon till the time servers don't respond. This can be achieved using ngIf.
  • You can use resolver as pointed out by @Rajez.
  • You can use async pipe on your table so that angular knows that it need to subscribe on data and wait instead of displaying the empty table.

Hope this helps! If you need code snippet for any of the approaches do mention in comment.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM