1

I am trying to update the array value but inside httpClient method it is working But it is not working outside. So, how to resolve this issue in angular 14.

app.component.ts:

  ngOnInit(): void {
      this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
      this.groupData = data;
      console.log(this.groupData); // it should be data.json value
  }); 
   
  }

Demo : https://stackblitz.com/edit/angular-ivy-1hqg9x?file=src%2Fapp%2Fapp.component.ts

EMahan K
  • 417
  • 1
  • 19
  • You are trying to log sync a value from an async call. – MoxxiManagarm Jul 12 '22 at 12:19
  • 2
    You don't need httpClient to get data from an asset – nicolascolman Jul 12 '22 at 12:20
  • not, you get the value **inside** subscribe function an httpClient.get is async, that main that Angular only call to execute the action, then continue running your code it's the reason you get an empty value outside subscribe function – Eliseo Jul 12 '22 at 12:20
  • @Eliseo :Can you edit my stackblitz? – EMahan K Jul 12 '22 at 12:26
  • @EMahanK, [here](https://stackblitz.com/edit/angular-ivy-hbdrtu?file=src%2Fapp%2Fapp.component.ts) NOTE: you should use a service instead of use the httpClient in the component. The reason is to have "separate" the component of the call to the API. In a future you could change the file or you get the data from a dbs. It's more comfortable change the service that the component (and avoid errors) – Eliseo Jul 12 '22 at 16:37

1 Answers1

3

The observable is resolved asynchronously and thus your log-message is written before the http call returns

ngOnInit(): void {
      this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
      this.groupData = data;
      console.log(this.groupData); // now you see the resolved data
  }); 
}
TmTron
  • 17,012
  • 10
  • 94
  • 142
  • Not Working: https://stackblitz.com/edit/angular-ivy-ctyjxa?file=src%2Fapp%2Fapp.component.ts – EMahan K Jul 12 '22 at 13:05
  • working: https://stackblitz.com/edit/angular-ivy-nxdkqd?file=src%2Fapp%2Fapp.component.ts – TmTron Jul 12 '22 at 14:21
  • @EMahanK and TmTron: should be **this.httpClient.get('assets/data.json')**. See that "assets has no `../`. When you build an Angular app (`ng build`) by defect create the index.html, the bundles files (the javascript and the .css) in a folder `dist`. Angular copy also the assets folder in `dist/assets`, (you can change in angular.json).The index.html (also by defect) has a `` so all are reffered to the "dist" folder. So you use `/assets` or `assets` but **not** ../assets. see [stackblitz](https://stackblitz.com/edit/angular-ivy-hbdrtu?file=src%2Fapp%2Fapp.component.ts) – Eliseo Jul 12 '22 at 16:28
  • This happens also when you use a ``. – Eliseo Jul 12 '22 at 16:39