It is important that your component does not handle any http
requests directly; instead, utilize a service
for this purpose.
@Injectable({...})
export class MyService {
constructor(private http: HttpClient) {}
getData(): Observable<string[]> {
return this.http.get<string[]>('../assets/data.json');
}
}
In your component, to access 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));
}
}
Alternatively, if necessary, let the template HTML handle the response 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, keep in mind that when subscribing to an observable, the code will execute sometime later due to it being asynchronous
:
someFunction(): void {
console.log(1);
this.myservice.getData().subscribe(console.log(2));
console.log(3);
}
The output from the above code would be 1, 3, 2