Home > Software engineering >  How to update array values inside httpClient method in angular14
How to update array values inside httpClient method in angular14

Time:07-12

Trying to update the array value using the httpClient method. But not working properly. How to get that updated array value outside of httpclient method.If anyone knows please help to find the solution.

app.component.ts:

  public allData = ['Van1', 'Hills2', 'Root3'];
  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
     this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
     this.allData = data;
    });

    console.log(this.allData); // it should be data.json data
  }

Demo : https://stackblitz.com/edit/angular-ivy-zpvafg?file=src/app/app.component.ts

CodePudding user response:

You should print the console log inside the httpClient subscribe. Try this you will get the updated data.

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

CodePudding user response:

Your component shouldn't handle any http requests, for that, you need to use a service.

@Injectable({...})
export class MyService {
   constructor(private http: HttpClient) {}   

   getData(): Observable<string[]> {
     return this.http.get<string[]>('../assets/data.json');
   }
}

Then, in your component, in order to get the updated data list, you can either subscribe within the component:

@Component({...})
export class MyComponent implements OnInit {
  constructor(private myService: MyService){}

  ngOnInit(): void {
    this.myService.getData().subscribe(data => console.log('Response: ', data));
  }
}

Or let the template HTML if necessary to handle the response by using the async pipe:

@Component({...})
export class MyComponent implements OnInit {
  theDataFromTheBackend$!: Observable<string[]>;

  constructor(private myService: MyService){}

  ngOnInit(): void {
    this.theDataFromTheBackend$ = this.myService.getData();
  }
}
<ng-container *ngIf="theDataFromTheBackend$ | async as result">
  <div> {{ result | json }} </div>
</ng-container>

Additionally, when you subscribe to any observable, that piece of code in that moment will execute some time later because is asynchronous:

someFunction(): void {
  console.log(1);
  
  this.myservice.getData().subscribe(console.log(2));

  console.log(3);
}

The output from above will be 1, 3, 2

  • Related