💻 Tech
Similar to RxJS, you can work on asynchronous data with EventEmitter, which is available from angular/core
.
For example, the API service below creates an EventEmitter that can be subscribed to by other components. AppComponent can use the data like render it on the UI once it’s available. The data will only become available once there’s some data emitted to the EventEmitter being subscribed to, which is dataFetched
. In the example, after 5 seconds, fetchData
is called to simulate data fetch that takes some time or that takes place at another time. Once data is emitted, all the parts of the code that are subscribed to dataFetched
can now use it.
// api.service.ts
export class ApiService {
public dataFetched = new EventEmitter<any>();
constructor(private http: HttpClient) {}
fetchData() {
this.http.get('https://api.github.com/users/someuser')
.subscribe(
(data) => this.dataFetched.emit(data),
(error) => console.error('Error fetching data', error)
);
}
}
// app.component.ts
export class AppComponent implements OnInit {
data: any;
constructor(private apiService: ApiService) {}
ngOnInit() {
this.apiService.fetchData();
this.apiService.dataFetched.subscribe((fetchedData: any)=> {
this.data = fetchedData
})
// Simulates other parts of the program that triggers fetch at some point, or some wait time
setTimeout(() => {
this.apiService.fetchData();
console.log("done");
}, 5000)
}
}