简体   繁体   English

防止在 angular 8 中多次运行相同的服务

[英]prevent running same service multiple times in angular 8

So I am having three button(A,B) that is calling the same services to get the same data.所以我有三个按钮(A,B)调用相同的服务来获取相同的数据。 So I just want to call the service once, not matter how many times i'm click the button, what I did is to add a boolean to determine if the service has been called already, and if yes, then just the the existData that saved from the previous service.所以我只想调用一次服务,不管我点击了多少次按钮,我所做的是添加一个布尔值来确定服务是否已经被调用,如果是,那么就只是存在数据从以前的服务中保存。 Below are my code, however, I am not able to get the updated boolean value and data when I click the button the second time or third time.下面是我的代码,但是,当我第二次或第三次单击按钮时,我无法获得更新的布尔值和数据。

ts file .ts 文件

exist: boolean = false;
buttonName : string;
postData: any = [];
data: any; = []
existData: any = [];
constructor(){}
ngOnInIt(){
   if(buttonName == "A"){
     if(this.exist == true){              // this.exist is always false no matter how many times button click
       this.existData();
     }else{
       this.getData();
     }
   }else if(buttonName == "B"){
     if(this.exist == true){
       this.existData();
     }else{
       this.getData();
     }
   }
}
getPostData(){
   this.postData.name = "Button";
   this.postData.parameters = [];
   this.exist = true;
}
getData(){
   this.getPostData();
   this.appService.getData(this.postData).pipe(first()).subscribe(data => {
      this.data = data;
      this.existData = data;
   })
}
existData(){
   console.log(this.existData)        // this is always []
}

first of all ngOnInIt is invoked only once, you have to call getData() on a button event and then set boolean to exist.首先 ngOnInIt 只被调用一次,你必须在按钮事件上调用 getData() ,然后设置布尔值存在。 If you just want to call getData once you can simply do it on ngOnInIt itself no need to check any other conditions.如果您只想调用 getData 一次,您可以简单地在 ngOnInIt 本身上执行此操作,无需检查任何其他条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM