首页 > 解决方案 > Angular 8 - 为什么客户端对后端进行多次 API 调用

问题描述

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

原因是什么,为什么以及如何解决?此外,如果后端尚未返回任何内容但仍在执行操作,则也会进行第二次调用。

这是一些代码示例:

方法调用服务:

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 });
}
}

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

标签: c#jsonangularrestclient

解决方案


这种情况可能有两个原因:正如您提到的,有两个对 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();
}

推荐阅读