Failed to put the data from service into window variable (this)

Viewed 68

I was trying to put the data[0] from ApiService to this.data.

However, it failed. Can anyone please guide me on this?

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../services/api.service';

@Component({
  selector: 'app-card-details',
  templateUrl: './card-details.component.html',
  styleUrls: ['./card-details.component.scss']
})
export class CardDetailsComponent implements OnInit {
  name: string = "";
  data: any;

  constructor(
    private route: ActivatedRoute,
    private apiService: ApiService,
  ) { }

  ngOnInit() {
    this.getData();
  }

  getData(){ 
    this.route.params.subscribe(params => this.name = params['name']);
    this.apiService.getName(this.name).subscribe(data => {
      this.data = data[0];
      console.log(this.data); \\ console.log at here able to show the value of this.data
    })
    console.log(this.data); \\ console.log at here NOT able to show the value of this.data
  }
}
2 Answers

This happens because you are making an async call so the first time that you print this.data the information the information has not arrived yet. However when the async call receive the information then your console.log inside print information. As exercise put a button to call as soon as the asyn call has response put inside then a console.log printing this.data and you will see that the information are present.

 getData(){ 
   this.route.params.subscribe(params => this.name = params['name']);
   this.apiService.getName(this.name).subscribe(data => {
    this.data = data[0];
    console.log(this.data); \\ it prints when receive the data (async)
   })
   console.log(this.data); \\ it prints although the data is not prensent
}

If you want to wait for your service then use async and await in your method and make your apiservice to promise like following.

  ngOnInit() {
    this.getData();
  }

  async getData() {
    let data;
    await this.http
      .get("https://reqres.in/api/users?page=2")
      .toPromise()
      .then((datas: any) => {
        data = datas.data;
        console.log(data);
      });
    console.log(data);
  }

Now you can able to see the data's in both console logs Here the stackblitz demo : https://stackblitz.com/edit/angular-ivy-kspmyr?file=src/app/app.component.ts

Related