如何解决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>
解决方法
我在这里看到多个问题。
- 您不需要3个单独的订阅
ForEach
。您可以在单个订阅中分配所有属性
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 }); }
应该在订阅中。该变量是异步分配的,并且可能尚未分配任何值(如果它在预订范围之外)。 -
图像问题相同。变量
console.log(this.userProfile)
在this.imageSource
回调中被异步分配。因此,呼叫onload
应该在回调内部。
this.openDialog
您可以了解有关异步数据here的更多信息。
纯/不纯管道的概念也与Angular pipes相关,并且不适用于您在模板中未使用任何Angular管道的情况。如果您不熟悉Angular,建议您阅读他们的tutorial。它介绍了一些基础知识。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。