Angular observable 订阅属性

奈斯奎克

这是我如何设置它的一个简单视图,图像数组实际上在一个表单组中,它最终传递回 C# 后端

我希望检查images数组是否包含 4 个以上的元素,否则设置canAdd为 false,现在允许将更多图像添加到images数组中,一旦从数组中删除图像,则应再次允许

export class SomeComponent implements OnInit {
  images = []
  canAdd: Observable<boolean>
  

constructor() { }
}

如何设置订阅?在这个数组和可观察对象之间?

我正在像这样添加到图像数组

onFileChanged(files) {
  // Check here the observable if it canAdd

  if (files.length === 0)
    return;

  var mimeType = files[0].type;
  if (mimeType.match(/image\/*/) == null)
    return;

  var reader = new FileReader();
  reader.readAsDataURL(files[0]);
  reader.onload = (_event) => {
    this.images.push(reader.result);
  }
}
马特

我不知道您的具体用例,但根据您的逻辑,您可以通过几种不同的方式处理它。

例如,如果您在同一个组件中处理上传和显示,并且图像是该组件的公共属性,您可以这样做:

<input type="file" (change)="onFileChanged($event)" multiple *ngIf="images?.length < 4">

如果您在其他地方这样做,那么我会将逻辑移动到一个单独的服务,该服务将处理上传过程并告诉订阅者在图像数组更改时隐藏/显示输入,例如:

@Injectable({
  providedIn: 'root'
})
export class UploadService {

  constructor() { }

    //if you want to hold images here
    private images: any[] = [];

  //use this to emit values to show/hide input
  private canAddSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
  readonly canAdd$: Observable<boolean> = this.canAddSubject.asObservable();

  //you can use another subject and observable if you want subscribe to images array changes
  //this way will allow you to handle it in a more reative way
  private imagesSubject: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);
  readonly images$: Observable<any[]> = this.imagesSubject.asObservable();

  public onFileChanged(files): void {
    
      this.images.length > 4
        ? this.canAddSubject.next(false)
        : this.canAddSubject.next(true);

        //rest of the code omitted for brevity
    }
}

然后只需将服务注入您的组件并使用异步管道监听 canAdd$ 更改,例如:

<input type="file" (change)="onFileChanged($event)" multiple *ngIf="uploadService.canAdd$ | async">

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章