Search code examples
angularangular2-routingangular7

How to access variable which is inside subscribe in Angular


I have a problem of accessing a variable which is inside subscribed. Here I am including code and in ngOninit, I have service which returns object and from that object, I can able to get json which I want and then I am trying to store it in a variable and then I am trying to access that variable outside subscribe which I can not able to do it. So how can I use a variable outside subscribe.

ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');
    this.dataService.GetFormById(+id).subscribe(response => {
      console.log(response);
      const temp = response['TemplateJson'];
      var Data = temp;
    })

    initJq();
      var formData = Data

      this.formBuilder = (<any>jQuery('.build-wrap')).formBuilder({ formData });

     // Sample code to handle promise to get for data on page load directly
      this.formBuilder.promise.then(formBuilder => {
        console.log(formBuilder.formData);
      });
  }

In this code inside subscribe there are variable Data and in temp i have json so how can i store that Data in formData variable.


Solution

  • This is pretty straight forward,

    data: any;
    ngOnInit() {
        const id = this.route.snapshot.paramMap.get('id');
        const that = this;
        this.dataService.GetFormById(+id).subscribe(response => {
          console.log(response);
          // const temp = response['TemplateJson'];
          that.data = response['TemplateJson'];
        })
    
      }
    

    Since this is asynchronous this.data must check before using if its defined or not, or you can do whatever you want inside the asynchronous callback which is inside the subscription block where data get initialized.

    Example

    data: any;
    ngOnInit() {
        const id = this.route.snapshot.paramMap.get('id');
        const that = this;
        this.dataService.GetFormById(+id).subscribe(response => {
          // this is an asynchronous callback
          console.log(response);
          // const temp = response['TemplateJson'];
          that.data = response['TemplateJson'];
          that.generateForm();   // calling method after initializing the this.data variable
        })
      }
    generateForm() {
        // just copying your question content to give you an idea
        const formData = this.data;
        this.formBuilder = (<any>jQuery('.build-wrap')).formBuilder({ formData });
        this.formBuilder.promise.then(formBuilder => {
        console.log(formBuilder.formData);
      });
    }