Angular Cli:如何阻止服务器发送连续请求?

Angular Cli:如何阻止服务器发送连续请求?,angular,angular-cli,Angular,Angular Cli,在宣布以前的结果之前,如何停止第二个请求?在角度Cli中 例如,引号 这是我的quotes.component.ts: import { Component, OnInit } from '@angular/core'; import { Response } from '@angular/http'; import {Quote} from "../quote.interface"; import {QuoteService} from "../quote.service"; @Compo

在宣布以前的结果之前,如何停止第二个请求?在角度Cli中


例如,引号

这是我的quotes.component.ts:

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import {Quote} from "../quote.interface";
import {QuoteService} from "../quote.service";

@Component({
    selector: 'app-quotes',
    templateUrl: './quotes.component.html',
    styleUrls: ['./quotes.component.css']
})
export class QuotesComponent implements OnInit {
    quotes:Quote[];
    loading = false;
    busy = false;


    constructor(private quoteService:QuoteService) {
    }

    ngOnInit() {
    }

    onGetQuotes() {
        if (this.busy == false) {
            this.loading = true;
            this.busy = true;
            this.quoteService.getQuotes()
                .subscribe(
                    (quotes:Quote[]) => this.quotes = quotes,
                    (error:Response) =>console.log(error),
                    this.loading = false,
                    this.busy = false
                );
        }else{
            alert('continuous request')
        }
    }


}
如您所见,我将“busy=false;”设置为

如果busy==false,则运行代码 但当我发送另一个请求时,两次或更多。。。服务器接受所有请求


在宣布以前的结果之前,如何停止第二个请求?

假设
QuoteService.getQuotes()
返回一个
rxjs/Observable
subscribe
方法具有以下签名:
Observable.subscribe([successCallback,errorCallback,completeCallback])
。行
this.loading=false;this.busy=false
既不属于
成功回调
也不属于
错误回调
;它们会立即执行,实际上您将四个参数传递给
subscribe

展开两个回调中的代码以包括以下两行:

this.quoteService.getQuotes().subscribe(
    (quotes:Quote[]) => {
        this.quotes = quotes;
        this.loading = false;
        this.busy = false;
    }, 

    (error: Response) => {
        console.log(error);
        this.loading = false;
        this.busy = false;
    });
或者,最好最后使用

this.quoteService.getQuotes()
.finally(() => {
    this.loading = false;
    this.busy = false;
})
.subscribe(
    (quotes:Quote[]) => this.quotes = quotes, 
    (error: Response) => console.log(error)
);

你说的“第二个”请求在哪里?此外,您的布尔标志在收到响应之前设置,因为这是异步的。当您单击submit B时,第二个请求刚好发生。这是异步的,因此在请求发生时,您会立即将布尔标志设置为
false
,完成时不会:)此链接有助于理解异步性: