2017-08-10 60 views
1

我有一個組件來創建或編輯旅行,我想要使用相同的形式。如果有任何參數,我如何提前檢查?Angular2條件switchMap和patchValue

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

    } 

    ) 

} 

回答

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

}

+0

現在,我得到這個錯誤:「錯誤TypeError:this.route.paramMap.filter不是函數「 – John

+1

您需要包含該函數的rxjs導入在你的進口報表 –

+0

非常感謝,通過導入'rxjs/add/operator/filter'工作。我只需要將驗證從「未定義」更改爲「空」。 – John