Angular 角度:将值从承诺分配给外部变量的问题

Angular 角度:将值从承诺分配给外部变量的问题,angular,typescript,firebase,Angular,Typescript,Firebase,我正在尝试将多张图片上载到firebase存储(从存储base64字符串的数组中),获取下载URL并将值分配到另一个数组中(在上载到cloud firestore之前) testuploadpic(){ this.skillImage=this.photoService.photos;//忽略此 对于(设i=0;i这里我们有几个典型的新手问题: 你失去了背景 使用嵌套异步函数时,没有将循环变量存储到闭包中 您正在尝试将异步API编写为同步API 你违背了诺言 尝试以下方法(未测试): 使用箭

我正在尝试将多张图片上载到firebase存储(从存储base64字符串的数组中),获取下载URL并将值分配到另一个数组中(在上载到cloud firestore之前)

testuploadpic(){
this.skillImage=this.photoService.photos;//忽略此

对于(设i=0;i这里我们有几个典型的新手问题:

  • 你失去了背景
  • 使用嵌套异步函数时,没有将循环变量存储到闭包中
  • 您正在尝试将异步API编写为同步API
  • 你违背了诺言
尝试以下方法(未测试):


使用箭头函数您的意思是
ref.getDownloadURL()。然后(url=>{this.skillImageURL[i]=url;})
?仍然没有定义。尝试在这个之前打印i.skillImageURL[i]=url;它得到0,就像我在for循环语句中为它分配的一样。您需要替换这两个
然后(函数(…){…}
带有箭头函数。
函数将更改上下文,因此
不再与周围的类(但与函数体)相关。箭头函数保留上下文。
  testuploadpic() {
    this.skillImage = this.photoService.photos; //ignore this
    for (let i = 0; i<this.skillImage.length; i++) {
      try {
        const id = Math.random().toString(36).substring(2);
        const file = this.skillImage[i];
        const filePath = `user-skill-images/${this.session.uid}_skill_${id}`;
        const ref = firebase.storage().ref(filePath);
        ref.putString(file, 'base64', {contentType:'image/jpeg'}).then(function(snapshot) {
          console.log('Uploaded');
          ref.getDownloadURL().then(function(url) {
            console.log(url)   //I can get the url
            this.skillImageURL[i] = url;   //Problem is at here
            console.log(this.skillImageURL);   //I get undefined
          })
        })
      } catch(e) {
        this.toastSvc.showToast(e);
      }
    }
  }
function testuploadpic(){
    this.skillImage = this.photoService.photos; //ignore this
    //returns array of urls
    return Promise.all(this.skillImage.map(i=>{
        const id = Math.random().toString(36).substring(2);
        const file = this.skillImage[i];
        const filePath = `user-skill-images/${this.session.uid}_skill_${id}`;
        const ref = firebase.storage().ref(filePath);
        return ref.putString(file, 'base64', {contentType:'image/jpeg'}).then((snapshot)=> {
            console.log('Uploaded');
            return ref.getDownloadURL().then((url)=>{
                console.log(url)   //I can get the url
                return url;   //Problem is at here
            })
        }).catch(err=>{
            this.toastSvc.showToast(err);
        })
    }));
}

testuploadpic().then(urls=> console.log(`Urls: ${urls}`));