I need to call function only when is first function loaded ? I have choice which work ( but not enough good for me )
allData(){
}
Do I have any better solution ?
allData() performs an async operation so you need to call the second function when the getContactPerson() returns a value. In your case you need to call it in the next callback. Try to move the second function call inside the callback, as following:
allData(){
this.accountsService
.getContactPerson()
.subscribe(
(data: any) => {
console.log(data)
/* DO SOME STUFF HERE */
this.lastAddedItem(this.contacts, contact);
},
(err: Error) => console.log(err)
)
}
this.allData()
UPDATE
If you want to use the same function in onInit and after another event such as a button click, you can refactor you code to return an Observable and use it in multiple places.
allData = () => this.accountsService.getContactPerson();
ngOnInit(){
this.allData().subscribe(
(data: any) => { /* DO SOME STUFF HERE */ },
(err: Error) => console.log(err)
)
}
refreshList = () => {
this.allData().subscribe(
(data: any) => {
/* DO SOME OTHER STUFF HERE */
this.lastAddedItem(this.contacts, contact);
},
(err: Error) => console.log(err)
)
}
// This is just an example for an async call
anotherAsyncCall = () => {
this.allData()
.pipe(
switchMap((result) => this.contactService.makeAsyncCall())
)
.subscribe()
}
This is a classic case for using switchMap operator. First of all, do not subscribe in allData() method, instead just return the observable:
allData() {
return this.accountsService.getContactPerson();
}
then, use switchMap where you are calling allData():
ngOnInit() {
this.allData().pipe(
switchMap(data => {
// Do what you want to with the data.
// I am assuming that the data is either assigned to contacts
// or contact ... but I am not sure.
// Return if this method also returns an observable.
return this.lastAddedItem(this.contacts, contact);
// otherwise comment the above line & uncomment the below line:
// this.lastAddedItem(this.contacts, contact);
}
).subscribe( ... );
I believe that you are getting observable from this this.accountsService.getContactPerson() method, so I will suggest you please try this approach.
async ngOnInit() {
await this.loadAllData();
this.lastAddedItem(this.contacts, contact);
}
public async loadAllData() {
try {
let allDataResponse$ = this.accountsService.getContactPerson();
let allData = await lastValueFrom(allDataResponse$);
} catch(e) {
console.log(e);
}
}
allData()method