首页 文章

Angular2条件switchMap和patchValue

提问于
浏览
1

我有一个组件来创建或编辑Trips,我想使用相同的表单 . 如果有参数,我该如何提前检查?

ngOnInit() {

    this.trip = this.fb.group({
      id: '',
      name: ['', [Validators.required, Validators.minLength(2)]],
    });

    this.route.paramMap
    .switchMap((params: ParamMap) => this.tripService.getTrip(+params.get('id')))
    .subscribe((trip: any) => {
        this.trip.patchValue({
          id: trip.id,
          name: trip.name
        });
    })
}

我已经尝试过这样的事情,但没有成功

ngOnInit() {

    this.trip = this.fb.group({
      id: '',
      name: ['', [Validators.required, Validators.minLength(2)]],
    });

    this.route.paramMap
    .switchMap((params: ParamMap) => {
         console.log(params.get('id'))
      if(params.get('id')){

          this.tripService.getTrip(params.get('id')).subscribe((trip: any) => {
              this.trip.patchValue({
                id: trip.id,
                name: trip.name
              });
          })
        }

    }

    )

}

1 回答

  • 3

    类似的东西怎么样:

    this.route.paramMap
    .filter(params => params.get('id') !== undefined)
    .switchMap((params: ParamMap) => this.tripService.getTrip(+params.get('id')))
    .subscribe((trip: any) => {
        this.trip.patchValue({
          id: trip.id,
          name: trip.name
        });
    })
    

    }

相关问题