代码之家  ›  专栏  ›  技术社区  ›  John

Angular2条件开关映射和patchValue

  •  1
  • John  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  3
  •   Dean Chalk    7 年前

    类似这样的东西怎么样:

    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
        });
    })
    

    }