属性的角度可观察子项

时间:2020-10-31 13:30:26

标签: angular rxjs

这是我如何进行设置的简单视图,图像数组实际上位于一个表单组中,该表单最终传递回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);
  }
}

1 个答案:

答案 0 :(得分:1)

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

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

<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">