-1

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);
   }
  }  
rafa_pe
  • 155
  • 1
  • 4
  • 15
  • 1
    I don't understand your point, the `cargar()` is asynchronous, so if you call `otraFunction()` before it load, you will have `undefined`. Do you need to call `otraFunction()` from a template or something like that? – Cristian18 Oct 06 '21 at 15:11
  • yes, I forgot to put the function this.otraFuncion() inside ngOnload :___ (edit) – rafa_pe Oct 06 '21 at 15:30
  • 1
    Your code it correct, but this.miVariable will stay undefined till the subscription is completed. The best solution here is to call this.otraFuncion(); inside the subscribe callback. – msleiman Oct 06 '21 at 16:20
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Oct 08 '21 at 10:53

2 Answers2

1

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.

bryan60
  • 28,215
  • 4
  • 48
  • 65
0
   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().

vsnikhilvs
  • 456
  • 1
  • 3
  • 10