I'm facing a challenge with a function that returns a value known as user_id
. It involves multiple conditions that need to be checked.
First condition: Verify the service variable
Second condition: If not found, retrieve user_id
from local storage
Third condition: If still not found, get firebase_uid
from local storage, then invoke the function findUserId(firebase_uid)
to get the user_id
Fourth condition: If all else fails, obtain uid
from Firebase and call findUserId(uid)
Below is the code snippet.
export class UserService {
user_id : any;
firebase_uid: any;
id: any;
returnUser_id() {
if(this.user_id) {
return this.user_id
}
else {
this.storageService.get('user_id').then(val =>{
if(val) {
this.user_id =val
return this.user_id
}
else {
this.storageService.get('firebase_uid').then(value =>{
if(value) {
this.firebase_uid = value
this.findUserId(this.firebase_uid).subscribe(q =>{
console.log(q)
this.id = q;
for(let i =0; i<this.id.length;i++) {
this.user_id = this.id[i].id
return this.user_id
}
this.storageService.set('user_id', this.user_id ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});
})
}
else {
this.afauth.authState.subscribe(user =>{
if(user) {
this.firebase_uid = user.uid;
this.storageService.set('firebase_uid', this.firebase_uid ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});
this.findUserId(this.firebase_uid).subscribe(data =>{
this.id = data;
for(let i = 0 ;i<this.id.length; i++ ){
this.user_id = this.id[i].id
return this.user_id
}
this.storageService.set('user_id', this.user_id ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});
})
}
})
}
}).catch(err =>{
console.log(err)
})
}
}).catch(err =>{
console.log(err)
})
}
}
}
Function for finding User ID
findUserId(uid): Observable<any> {
return this.http.get<User[]>(this.user_url + 'users?filter[fields][id]=true&filter[where][firebase_uid]=' +uid )
}
This code snippet may appear convoluted and challenging to comprehend. Are there any alternatives to using conventional if-else statements?
I appreciate any insights in advance