c# - 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 });
}
}
我希望足够清楚,但如果我不自由地问我更多细节。非常感谢!
解决方案
这种情况可能有两个原因:正如您提到的,有两个对 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();
}
推荐阅读
- java - 将 rsa 私钥分成两半
- jenkins - 如何使用 ansible 或其他工具为 Jenkins 自动配置 LDAP 和其他插件
- c++ - 在 VS 17 中运行加载转储文件的代码不兼容
- python - OpenGL绘制区域仅占据可用窗口的左下象限
- java - 使用Java中的do-while循环查找序列的所有元素的总和,以数字0结尾
- macos - 在 Ubuntu 服务器上安装 Mac-OS
- apache-spark - PySpark:带前缀/后缀的选择
- python - Django:帮助理解信号函数
- java - 在 Android 的另一个 Activity 中启动 Activity
- python - 如何不收到“无类型”错误消息