Angular - FileReader() 没有得到任何路径

Angular - FileReader() dont get any path

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

这很奇怪,有时它会起作用,但大多数时候我的变量是空的...我认为它是随机的,因为我没有找到获得 URL.

的模式

这个component.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 个单独订阅 route。您可以在单个订阅中分配所有属性
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
  });
}
  1. 此外,console.log(this.userProfile) 应该在订阅内。该变量是异步分配的,如果它在订阅之外,可能还没有分配任何值。

  2. 图像的问题也是一样。变量 this.imageSourceonload 回调中被异步赋值。所以调用 this.openDialog 应该在回调中。

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: any) => {
      this.imageSource = reader.result;
      this.openDialog(this.imageSource); // <-- should be inside the callback
    }
  }
}

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

pure/impure 管道的概念也与 Angular pipes and it doesn't apply to you seeing that you aren't using any Angular pipe in the template. If you're new to Angular, I'd recommend you to go through their tutorial 有关。它介绍了一些基础知识。