微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular-FileReader没有得到任何路径

如何解决Angular-FileReader没有得到任何路径

我尝试在对话框中传递图像,用户可以在该对话框中通过cropperjs裁剪图像,然后可以上载图像,但有时FileReader()没有任何路径。

这很奇怪,有时它可以工作,但是大多数时候我的变量为空...我认为这样做是随机的,因为我没有找到获取URL的模式。

此组件。ts

  constructor(private route: ActivatedRoute,public dialog: MatDialog,) { }
  @input() user: any
  @input() userProfile: any
  @input() userPosts: any
  imageSource: any = null;

  ngOnInit(): void {
    this.route.data.subscribe((data: {user: any}) => { this.user = data.user;});
    this.route.data.subscribe((data: {userProfile: any}) => { this.userProfile = data.userProfile;});
    this.route.data.subscribe((data: {userPosts: any}) => { this.userPosts = data.userPosts;});
    console.log(this.userProfile)
  }

  openDialog(src:string): void {
    const dialogRef = this.dialog.open(UserImgDialogComponent,{
      width: '500px',minHeight: '350px',data: src,});

    dialogRef.afterClosed().subscribe(result => {
      if(result) {
        console.log('Yes')
      }
    })
  }

  uploadFile($event) {

    if ($event.target.files && $event.target.files[0]) {
      const file = $event.target.files[0];

      const reader = new FileReader();
      reader.readAsDataURL(file)
      reader.onload = e => this.imageSource = reader.result;
      this.openDialog(this.imageSource);
    }
}

}

这是我的html

 <div class="UserImageDiv">
        <img [src]="userProfile.profileImagePath" class="UserImage">
        <button mat-icon-button matTooltip="Profilbild ändern" class='changeUserImg' (click)="uploader.click()">
          <mat-icon>add_a_photo</mat-icon>
        </button>
        <input hidden type="file" #uploader (change)="uploadFile($event)" />
      </div>

有人可以帮助我吗? 还有另一种获取图片上传路径的方法吗?

解决方法

我在这里看到多个问题。

  1. 您不需要3个单独的订阅ForEach。您可以在单个订阅中分配所有属性
route
  1. 此外,ngOnInit(): void { this.route.data.subscribe((data: any) => { this.user = data.user; this.userProfile = data.userProfile; this.userPosts = data.userPosts; console.log(this.userProfile); // <-- should be inside the subscription }); } 应该在订阅中。该变量是异步分配的,并且可能尚未分配任何值(如果它在预订范围之外)。

  2. 图像问题相同。变量console.log(this.userProfile)this.imageSource回调中被异步分配。因此,呼叫onload应该在回调内部。

this.openDialog

您可以了解有关异步数据here的更多信息。

纯/不纯管道的概念也与Angular pipes相关,并且不适用于您在模板中未使用任何Angular管道的情况。如果您不熟悉Angular,建议您阅读他们的tutorial。它介绍了一些基础知识。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?