angularsubscribengoninit

Can't get value in ngoninit on subscribe angular


I don't understand why my object is always "undefinned" on ngoninit on angular. I request on my api project i get my response correctly. When I console.log my object is not defined (ngoninit) but in other function i can get values.

My questions is why and how can i do to get my object in ngoninit.

Thank you

I retrieve my response correctly on postman others functions retrieve too

Service:

getById(id:string):Observable<Grower>{
   return this.http.get<Grower>(`${environment.apiUrl}/growers/${id}`);
}

View model:

export class GrowerDetails {

    adress:string;
    zip:string;
    city:string;
}

Component:

  growerService:GrowerService;

  detailsProfil: GrowerDetails;

  constructor(private authenticationService: AuthenticationService, growerService:GrowerService,
    private formBuilder:FormBuilder) { 
      this.growerService = growerService;
   }

  ngOnInit() {
    this.detailsProfil = new GrowerDetails();

    this.growerService.getById(this.decoded.nameid).subscribe(
      (data:Grower) => this.detailsProfil = {
            adress: data.adress,
            city: data.city,
            zip : data.zip

      },
      error => console.log(error) 
    );
console.log(this.detailsProfil); // undefinned

onSubmit(){
    console.log(this.detailsProfil); // ok
 }

Postman:

{
    "lat": 0,
    "long": 0,
    "description": "test",
    "adress": "test",
    "zip": "test",
    "city": "test"
}

Solution

  • We can have the value of detailsProfil inside the subscription but not outside of it. Because getById() is an async call so, won't wait for subscribe to finish before it executes.

    Do some changes like below,

     constructor(private authenticationService: AuthenticationService, growerService:GrowerService,
        private formBuilder:FormBuilder) { 
          //  this.growerService = growerService;  <- this line not required
       }
    
      ngOnInit() {
        this.detailsProfil = new GrowerDetails();
    
        this.growerService.getById(this.decoded.nameid).subscribe((data) => {
           console.log(data);            
           this.detailsProfil.adress = data.adress;
           this.details.city = data.city;
           this.details.zip = data.zip;
         },
          error => console.log(error));
         console.log(this.detailsProfil); // you will get detailsProfil Object
      }
    

    Happy Coding.. :)