【问题标题】:Angular 7 componentAngular 7 组件
【发布时间】:2019-04-30 04:39:34
【问题描述】:

我需要将名为“photos”的数组从我的 component.ts 传递到 component.html。这是我的 component.ts 文件

export class PhotosComponent implements OnInit {
public photos:any[]
constructor(){}
ngOnInit(){

 S3.listObjects({Delimiter: '/'}, function(err, data) {

  var albumName
if (err) {
  return alert('There was an error listing your albums: ' + err.message);
} else {
    console.log(data.CommonPrefixes)

  var albums = data.CommonPrefixes.map(function(commonPrefix) {
   //   console.log(albums)
    var prefix = commonPrefix.Prefix;
    console.log(prefix)
    albumName = decodeURIComponent(prefix.replace('/', ''));
    console.log(albumName)
    this.photos.push(albumName)
  });

  }


});
console.log(this.photos)

}

在 this.photos.push(albumName) 行,它显示“无法读取未定义的属性‘照片’”而且我无法将数据传递给 html。任何帮助将不胜感激。提前致谢

【问题讨论】:

    标签: javascript angular typescript angular7


    【解决方案1】:

    您的this 具有不同的范围,因为您处于回调函数中。解决此问题的最简单方法是改用 arrow functions

    function(err, data) 更改为(err, data) =>,将function(commonPrefix) 更改为(commonPrefix) =>

    另一个(旧)解决方案是将this 绑定到函数或将this 存储在不同的局部变量中。

    【讨论】:

    • 这解决了我的问题。感谢你的回答。但是,它开始为“推送”抛出相同的错误。你有什么建议我也可以解决这个问题吗? "无法读取未定义的属性 'push'"
    • 当然。你只是定义了变量photos,但你从来没有给它赋值。您可以通过将行更改为 public photos:any[] = []; 在声明时对其进行初始化 - 这意味着它使用空数组进行初始化。
    • 修复了错误,但 this.photos.push(albumName) 没有将专辑名称推送到数组中。它仍然是空的。仅当我执行 this.photos = albumName 时,才将最后一个相册名称传递给该值。我需要传递整个专辑名称数组。任何建议
    • 我自己解决了这个问题。在它完成将名称推送到它之前,我正在调用该数组。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2019-07-05
    • 2019-05-09
    相关资源
    最近更新 更多