Home > database >  Angular 2: Set value to a variable from one function and get it in another in the same class
Angular 2: Set value to a variable from one function and get it in another in the same class

Time:10-07

I need to set myVariable value indicated inside the function load(), where I collect a data from the service and show it in another function (otrafuncion()), but I don't know the syntax.

export class clase{

  public this.miVariable:any;

   constructor(){}

   ngOnload():void{
     this.load();
     this.otraFuncion();
   }

   load() {
     this.loadService.cargar().subscribe(
     (respuesta) => {
         this.carga = respuesta;
         this.miVariable=this.carga.mivalorRecogido; //necesito este valor
       }
      );
     }
    }

   otrafuncion(){
   console.log(this.miVariable);
   }
  }  

CodePudding user response:

   load() {
     this.loadService.cargar().subscribe(
     (respuesta) => {
         this.carga = respuesta;
         this.miVariable=this.carga.mivalorRecogido; //necesito este valor
         this.otrafunction(this.miVariable);
       }
      );
     }
    }

   otrafuncion(data: any){
   console.log(data); -> You will get miVariable here
   }

Also, in ngOnInit, if you call otrafunction, it would return undefined, since there is no data initially passed. First, you have to call load().

CodePudding user response:

if I can suggest a solution, your variable that you're interested in should be an observable, since it's only available asynchronously.

export class clase{
  public carga$ = this.loadService.cargar().pipe(shareReplay(1))
  public miVariable$ = this.carga$.pipe(map(c => c.mivalorRecogido));
}  

now when you're interested in either of these properties, you just subscribe to them. the shareReplay operator will ensure your value is cached and only requested once, and will only be requested when it is first needed.

  • Related