Angular 8 - 为什么客户端对后端进行多次 API 调用

Angular 8 - Why client makes multiple API calls to back-end

我有一个经典的客户端应用程序 API 调用服务器以对数据库进行操作。但出于某种原因,服务中的每个客户端方法都会在我只需要一次时调用我的控制器。

这是什么原因,为什么以及如何解决?此外,如果后端没有 return 任何东西但仍在执行操作,也会出现第二个调用。

这是一些代码示例:

方法调用服务:

export class TestingComponent implements OnInit {

results: any;

constructor(
private testingservice: TestingService) { }

ngOnInit() {
let test = true;
this.startingMethod(test);
 }

startingMethod(test) {
    this.testingservice.getData(test).subscribe( data => {
        this.results = data;
  })};
}

服务方式:

export class TestingService{

constructor(private configService: ConfigService, private http: HttpClient) { }

getData(test: boolean): Observable<any> {

let urlc = this.configService.getCurrentEndpoints();
let params = new HttpParams();
params = params.set('test', test);
return this.http.get<any>(`${urlc.baseUrl}${urlc.getdata}`, {'params': params });
}
}

我希望已经足够清楚了,但如果我不自由地问我更多细节的话。非常感谢!

这种情况可能有两个原因: 正如您提到的,有两个 BE 调用,也许其中一个是预检请求。 你可以在这里阅读:https://livebook.manning.com/book/cors-in-action/chapter-4/

第二个原因可能是多次订阅:

您可以更改服务调用方式,例如:

startingMethod(test) {
    this.testingservice.getData(test).toPromise().then( data => {
        this.results = data;
  })}

或者您可以使用订阅对象,例如:

subscription = new Subscription();

startingMethod(test) {
this.subscription.add(
    this.testingservice.getData(test).subscribe( data => {
        this.results = data;
  }));
}

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

Moreover, the second call comes also if the back-end didn't return anything yet but still performing the operation.

我怀疑您指的是 OPTIONS 请求。那是浏览器自己生成的CORS预检请求,完全正常。

OPTIONS 请求就是我们在 Cross-origin resource sharing (CORS).

中所说的飞行前请求

当您在特定情况下跨不同来源发出请求时,它们是必需的。

这似乎是浏览器的一个错误,他们发送了第二个请求来获取页面的图标,由于他们没有,所以它带来了任何东西。

这是针对 Chrome 错误的 link。 https://bugs.chromium.org/p/chromium/issues/detail?id=39402

Firefox 和大多数其他浏览器在首次连接时也会发出对网站图标的请求,但会缓存结果,即如果第一次没有返回网站图标,它们就不会继续尝试 - 这是为什么您只看到来自 Firefox 的单个请求。不幸的是,Chrome 对网站图标的要求有点太过执着了。