2016-09-29 53 views
3

在做我的第一個Angular 2 CRUD練習時,我試圖重新使用我的編輯表單來添加新的和編輯現有的對象。

我有這種不當代碼:

this._route.params.forEach((params: Params) => { 
     let id = params['id']; 
     if (id) { 
     this._productService.getProduct(id) 
      .subscribe(
      product => this.product = product, 
      error => this.errorMessage = <any>error 
     ); 
     } else { 
     this.product = { 
      name: 'default name', 
      ean: '', 
      price: 0, 
      qty: 0, 
      imageUrl: '', 
      _id: '' 
     }; 
     } 

    }); 

    (<FormGroup>this.registerForm).setValue(this.product, {onlySelf: true}); 

...這也難怪不起作用 - 因爲if的一部分是同步,其他 - 異步。

我想優化代碼並將靜態默認對象模板轉換爲來自立即解析的Observable的值 - 基本上相當於$q.when(myVar)。我怎麼做?

回答

4

現在我知道它會是:

 return Observable.of({ 
      name: 'default name', 
      ean: '', 
      price: 0, 
      qty: 0, 
      imageUrl: '', 
      _id: '' 
     });