Угловая Firebase Получение ZoneAwarePromise - PullRequest
0 голосов
/ 21 января 2019

Я пытаюсь создать эту функцию для загрузки изображения профиля на странице профиля моего приложения, проблема в том, что я получаю ZoneAwarePromise в результате функции загрузки изображения. Я пробовал кучу разных вещей, но не могу изменить результат.

Кто-нибудь может мне помочь? Что я делаю не так?

uploadService.ts

pictureUpload(file: any, uid: string) {
    return this.afUpload.upload('profile/' + uid, file);
}

profile.component.ts

onCreateUser() {
    const picture = this.uploadService.pictureUpload(this.fileInput.nativeElement.files['0'], currentUserID).then(
      async (data) => {
        try {
          return data.ref.getDownloadURL();
        } catch {
          console.error();
        } finally {
          const email = this.userProfileForm.value.email;
          const firstName = this.userProfileForm.value.firstName;
          const lastName = this.userProfileForm.value.lastName;

          const userObj = {
            'uid': currentUserID,
            'email': email,
            'firstName': firstName,
            'lastName': lastName,
            'picture': picture
          };

          console.log('the object is');
          console.log(userObj);

          if (this.editMode) {
            return this.db.object('profile/' + currentUserID).update(userObj).then(
              () => {
                return this.presentToaster('Dados atualizados');
              },
              (e) => {
                this.presentToaster(e);
                console.error(e);
              }
            );
          } else {
            const load = await this.loadCtrl.create({
              message: 'Criando Usuario'
            });
            await load.present();
            return this.db.object('profile/' + currentUserID).set(userObj).then(
              () => {
                load.dismiss();
                return this.navCtrl.navigateRoot('news');
              },
              (error) => {
                load.dismiss();
                this.presentToaster(error);
                console.error(error);
              }
            );
          }
        }
      },
      (error) => {
        console.error(error);
      }
    );
  }

1 Ответ

0 голосов
/ 22 января 2019

Я наконец получил его.

Отказ от ответственности: Это мой первый проект Firebase, поэтому все описание ниже основано на моих наблюдениях.Если я что-то не так, пожалуйста, поправьте меня, я действительно хочу это понять.Спасибо:)

В основном, когда я получаю try, я ожидаю получить данные обратно, в данном случае data.ref.getDownloadURL().Поскольку это обещание, я использовал метод .then для получения «полных» данных, а затем запустил все остальное внутри этого ответа.Мне кажется, что эти данные существуют только там.

onCreateUser(uForm: FormGroup) {
    const currentUserID = this.userAuth.getCurrentUserID();
    let picture;
    this.uploadService.pictureUpload(this.fileInput.nativeElement.files['0'], currentUserID).then(
      async (data) => {
        try {
          data.ref.getDownloadURL().then(
            async (downloadURL) => {
              picture = downloadURL;
              const email = this.userProfileForm.value.email;
              const firstName = this.userProfileForm.value.firstName;
              const lastName = this.userProfileForm.value.lastName;

              const userObj = {
                'uid': currentUserID,
                'email': email,
                'firstName': firstName,
                'lastName': lastName,
                'picture': picture
              };

              if (this.editMode) {
                return this.db.object('profile/' + currentUserID).update(userObj).then(
                  () => {
                    return this.presentToaster('Dados atualizados');
                  },
                  (e) => {
                    this.presentToaster(e);
                    console.error(e);
                  }
                );
              } else {
                const load = await this.loadCtrl.create({
                  message: 'Criando Usuario'
                });
                await load.present();
                return this.db.object('profile/' + currentUserID).set(userObj).then(
                  () => {
                    load.dismiss();
                    return this.navCtrl.navigateRoot('news');
                  },
                  (error) => {
                    load.dismiss();
                    this.presentToaster(error);
                    console.error(error);
                  }
                );
              }
              //
            }
          );
        } catch (error) {
          console.error(error);
        }
      },
      (error) => {
        console.error(error);
      }
    );

  }
...