如何为Angular 2 HTTP调用添加延迟

时间:2016-08-31 20:54:48

标签: angular typescript angular2-http

我正在使用带有TypeScript的Angular 2来实现一个使用对REST服务器的HTTP调用的Web应用程序。

问题是一些GET调用比其他调用快,我必须在它们之前添加一些延迟。如何正确删除此延迟并妥善处理此问题?

例如,在我删除一个制造商(在下面的代码中)之后,我必须回到我可以看到所有制造商的视图(我在ngOnInit()中实现了GET调用)。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute }   from '@angular/router';
import { DataService } from '../../../data/data.service';
import { CallManufacturerServices } from '../calls/calls.service';
import { ManufacturerClass } from '../class/manufacturer.class';

@Component({
    templateUrl: './app/inventory/manufacturer/view/view.component.html',
    styleUrls: ['./app/inventory/manufacturer/view/view.component.css'],
    providers: [CallManufacturerServices]
})

export class ViewComponent implements OnInit, OnDestroy {
    private sub: any;
    private ServerData: ManufacturerClass = {
        ManufacturerId: 0,
        ManufacturerName: 'N/D',
        ManufacturerWebSite: 'N/D'
    };

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private data: DataService,
        private calls: CallManufacturerServices) {
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            let id = +params['id'];
            this.getSingleManufacturer(id);
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    private getSingleManufacturer(id: number) {
        this.calls.GetSingleManufacturer(id).subscribe(
            (data) => {
                this.ServerData = data.json();
            },
            error => console.log(error),
            () => console.log('getSingleManufacturer complete!')
       );
    }

    private deleteManufacturer(_manufacturer: ManufacturerClass) {
        this.calls.DeleteManufacturer(_manufacturer.ManufacturerId).subscribe(
            error => console.log(error),
            () => console.log('deleteManufacturer complete!')
        );
        /* this type of delay doesn't work */
        setTimeout(() => {}, 2000); // insert there the delay
        /* when I go to Manufacturer the Get call will start */
        this.goToManufacturer();
    }

    private goToManufacturer() {
        this.router.navigate(['/inventory/manufacturer']);
    }

    private goToEdit(manufacturer: ManufacturerClass) {
         this.router.navigate(['/inventory/manufacturer/edit', manufacturer.ManufacturerId]);
    }
}

1 个答案:

答案 0 :(得分:3)

只有在请求成功完成后才能导航Angular 2,因此:

this.calls.DeleteManufacturer(_manufacturer.ManufacturerId).subscribe(
        undefined, // onNext handler
        error => console.log(error), // onError handler
        () => { // onComplete handler
            console.log('deleteManufacturer complete!');
            this.goToManufacturer();
        }
    );