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