-3

Unable to assign data to a variable from http post method.

If we assign its resulting undefined.

Though I use promise method, subscribe method. If we print within subscription method, console will print data, there after when we assign to variable and print then it results undefined.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { RestuarantserviceService } from 'src/app/services/restuarantservice.service';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-restaurant-page',
  templateUrl: './restaurant-page.component.html',
  styleUrls: ['./restaurant-page.component.css']
})
export class RestaurantPageComponent implements OnInit {
  id;
  data:any;
  datacontainer:any;
  constructor( private router: Router, 
    private route: ActivatedRoute,private restuarantservice:RestuarantserviceService, private http:HttpClient) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.paramMap.get('id');
    
   this.getRestaurantData(this.id);
   console.log(this.datacontainer);
  }

  getRestaurantData(id){
    this.http.post('https://www.nearkart.com/api/nk/productList?lngId=1&token=',{
      branchCode: id,
        deliveryTypeCode: 1,
        serviceMasterId: 7
    }).subscribe((data:any)=>{
      this.datacontainer=data;
    })
  }

}

1 Answers1

0

Your console.log is right after your call to getRestaurantData. The fact is that you subscribe for a http request on this method, so you do something asynchronous, and so the console.log will not wait for the method to set data into this.datacontainer.

I suggest you to use this approach to subscribe

ngOnInit(): void {
  this.id = this.route.snapshot.paramMap.get('id');

  this.getRestaurantData(this.id).subscribe((data:any) => {
    this.datacontainer=data;
  },(error) => {
  },() => {
    console.log(this.datacontainer);
  })
}

getRestaurantData(id){
  this.http.post('https://www.nearkart.com/api/nk/productList?lngId=1&token=',{
    branchCode: id,
    deliveryTypeCode: 1,
    serviceMasterId: 7
  })
}

This way you wait for the subscribe to get all your message, which is you request data in your case.

Alexis
  • 1,685
  • 1
  • 12
  • 30