#angular #performance #rxjs #google-cloud-storage #ionic4
#angular #Производительность #rxjs #google-облачное хранилище #ionic4
Вопрос:
У меня есть эта функция, которая получает информацию из каждого запроса и передает ее следующему. Каков наилучший способ реализовать это. Это работает, но я боюсь, что в долгосрочной перспективе это может вызвать некоторые проблемы, учитывая, что у меня есть вложенные подписки.
onSubmit(){
this.loadingController.create({keyboardClose:true, message:'Submitting Info...'})
.then(loadingEl => {
loadingEl.present()
this.sharedService.uploadImage(this.state['image']).subscribe(imgUrl => {
this.sharedService.addVisitor(this.state['first_name'],
this.state['last_name'],
this.state['role'],
this.location,
imgUrl,
this.state['visitee_email'],
this.state['visitee_phone'],
this.state['visitee_name'],
this.state['company'])
.subscribe(visitor => {
console.log(visitor)
this.sharedService.addQuestionnaire(visitor.id)
.subscribe(questionnaire => {
console.log(questionnaire)
//dismiss the loading element
loadingEl.dismiss();
// navigate away
this.router.navigate(['/home'])
})
})
}, error => {
loadingEl.dismiss()
console.log(error)
this.alertController.create({header: "An error ocurred...",
message: "Could not submit visitor info.",
buttons: [{text: 'Okay', handler: () => this.router.navigateByUrl('/home')}]}).then(alertEl => {
alertEl.present()
})
})
})
}
}
- Я загружаю изображение, чтобы получить URL-адрес из облачного хранилища
- Сделайте еще один запрос, чтобы добавить посетителя и получить идентификатор посетителя
- после этого я загружаю существующую введенную анкету в другой api
если кто-то может уменьшить или помочь мне улучшить этот фрагмент кода, я буду очень признателен!
Ответ №1:
Вместо этого вы можете сделать это так:
import { switchMap, catchError, throwError } from 'rxjs/operators';
this.sharedService
.uploadImage(this.state['image'])
.pipe(
switchMap(imgUrl => this.sharedService
.addVisitor(
this.state['first_name'],
this.state['last_name'],
this.state['role'],
this.location,
imgUrl,
this.state['visitee_email'],
this.state['visitee_phone'],
this.state['visitee_name'],
this.state['company']
)
),
switchMap(({ id }) => this.sharedService.addQuestionnaire(id)),
catchError((error: any) => throwError(error))
)
.subscribe(
questionnaire => {
console.log(questionnaire)
loadingEl.dismiss();
this.router.navigate(['/home'])
},
error => {
loadingEl.dismiss()
console.log(error)
this.alertController.create({
header: "An error ocurred...",
message: "Could not submit visitor info.",
buttons: [{text: 'Okay',
handler: () => this.router.navigateByUrl('/home')}]}).then(alertEl => alertEl.present())
}
);