1

user.component.ts


ngOnInit(): void
  {
    var data;
    this.auth=this.cookie.get("auth");
    this.servicefetch.ContactList(this.auth).subscribe
    (
      (response)=>
      {
        data=response;
      },
      (error)=>{console.log(error)}

    );
  }

serviceCRUD.service.ts

 ContactList(auth:String)
 {
    const headers = { "content-type": "application/json", "Authorization": "Contacts " + auth };

    return this.http.get<any>('http://localhost:8080/contacts', {headers});
 }

Here I want to assign the response to the other variable say data. But when I print out the data I get undefined. I think it is because this is asynchronous. Any way I can assign it to the variable data

2 Answers2

1

You must declare your state variable in the scope of the class of Component.

export default App extends Component {

data: any;

ngOnInit(): void
  {
    this.auth=this.cookie.get("auth");
    this.servicefetch.ContactList(this.auth).subscribe
    (
      (response)=>
      {
        this.data=response;
       // call the next callback (store the token or go to next route)
      },
      (error)=>{console.log(error)}
    );
  }
}

You can check in the template like this:

<div *ngIf="data">
    data.yourProperty
</div>
1

As you have stated, http call is an asynchronous operation.

If we try below

let data;
this.servicefetch.ContactList(this.auth).subscribe({
  next: response => data = response
});
console.log(data);

Data will be undefined because this code is executed before the response is back.

In angular, the best way to handle the above would be to assign the observable to your variable Example below

  myData$ = this.servicefetch.ContactList(this.auth);

Now in your template and various operations you can use this observable. eg to display data in the template you may have

  <ng-container *ngIf='myData$ | async as data'>
    // data is now available here
  </ng-container>

In your TS file you can subscribe to this variable and perform other operations

  myData$.subscribe({ next: (data) => console.log(data)})
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74