2016-10-16 102 views
0

需要幫助!異步請求 - 指令後數據加載

我有一個組件'form.component.ts'。

------------- ------------- form.component.ts

@Component({ 
 
    selector: 'my-app', 
 
    providers: [ShopService], 
 
    templateUrl: 'app/admin/shop/shop-form/form.html' 
 

 
}) 
 

 
export class FormComponent implements OnInit { 
 
    private shop:Shop = new Shop(); 
 
    
 
    ... 
 

 
    this.route.params.subscribe(params => { 
 
    if (params['id'] !== undefined) { 
 
       this.shopService.getById(params['id']).subscribe(result => this.shop = result); 
 
       
 
     } 
 
    }); 
 
}

我' form.html'有一個指令,它有一個變量(shop.state),它依賴於在ajax中加載的數據。

------------- ------------- form.html

<state-city [state]='shop.state' (stateSelected)="shop.state = $event" [city]='shop.city' (cidadeSelected)="shop.city = $event"></state-city>

我的問題是,有時ajax請求需要很長時間來加載,我的指令是未定義的值。

我需要什麼指令加載後請求ajax返回的東西。

** EDITED **

我reducin我的代碼更好的視覺效果。 總結...我需要先發生請求ajax然後打印模板。我的<state [state]='shop'></state>需要這個變量才能正常工作。

我form.component是:

@Component({ 
 
    selector: 'my-app', 
 
    providers: [ShopService], 
 
    template: `<state [state]='shop'></state>` 
 

 
}) 
 
export class FormComponent { 
 
    private shop: string; 
 
    
 
    constructor(private shopService:ShopService) { 
 

 
     this.route.params.subscribe(params => { 
 
      
 
      this.shopService.getById(params['id']).subscribe(result => this.shop = result); 
 
     }); 
 
    } 
 
}

** 議決 **

問題解決了!我解決了使用方法ngOnChanges的角度2. 每個狀態改變都調用這個方法。也就是說,在ajax調用完成後,調用這個方法。因此我們更新了變量,我的指令運行良好。

回答

1

使用可以使用ngIf等待,直到你得到的數據,

<state-city *ngIf="shop" 
      [state]='shop.state' 
      (stateSelected)="shop.state = $event" 
      [city]='shop.city' 
      (cidadeSelected)="shop.city = $event"> 
</state-city> 
+0

是的,你說得對。 –

+0

甚至把'?'我的問題沒有解決。 解決包含一個新的註冊,因爲它不需要數據。精確編輯數據。 這就是...它在指令之後加載的數據。 –

+0

我的答案不能解決你的問題嗎? – micronyks