2017-07-18 54 views
3

我試圖複製一個財產角(志願者到X),因爲我想編輯的財產和離開志願者的方式。下面是從TS的代碼:如何將角度屬性複製到另一個?

volunteership; 
x ; 

constructor(private viewvolunteershipService: Volunteership, 
    private router: Router) {} 

ngOnInit() { 
    this.viewvolunteershipService.getVolunteership().subscribe(volunteership => 
     this.volunteership = volunteership); 
    console.log("Volunteership", this.volunteership); 
      this.x = this.volunteership; 
} 

在這裏,在HTML我想打電話給在ngFor的屬性x,所以我可以從中選擇一個城市,但它顯示了我什麼。如果我使用志願者而不是x,那麼它的工作是完美的。如何將志願者複製到x,以便我可以從中選擇一個城市?

<div class="form-group" > 
    <label for="city" >City</label> 
     <select id="city" class="form-group" > 
      <option value=""></option> 
      <option *ngFor=" let z of x" >{{z.city}}</option> 

     </select> 
    </div> 

我已經試圖複製一個數組

for (var i = 0, len = this.volunteership.length; i < len; i++) { 
    this.x[i] = this.volunteerhip[i]; 
} 

我甚至一直在使用Object.assign()方法,仍然沒有嘗試過。

+0

'subscribe'是異步的,這意味着'subscribe'之外的代碼在您調用服務時不會停止執行。如果你想使用你設定的'志願者'的數據,你需要在訂閱內部完成,或者保證你的服務已經取得了數據(例如在下拉菜單中調用'change'事件顯示使用'* ngIf =「志願者」') – snaplemouton

回答

1

首先,您需要按照以下說明在回調(subscribe)中進行分配:How do I return the response from an Observable/http/async call in angular2?但您提到您只希望更改反映在x陣列中。由於是,所有的改變將發生在這兩個陣列,xvolunteership一個參考,你很可能要使用Object.assign

ngOnInit() { 
    this.viewvolunteershipService.getVolunteership().subscribe(volunteership => { 
    this.volunteership = volunteership; 
    this.x = this.volunteership.map(obj => Object.assign({}, obj)) 
    }); 
} 

現在x陣列將不必到volunteership數組的引用。

+0

謝謝,它實際上工作!我想對x做出的改變仍然需要在訂閱中,對嗎? –

+0

是的,如果您需要在檢索數據後進行更改,您需要在'subscribe'內執行此操作:) – Alex

+0

您是否還知道如何將志願者身份保存在另一個對象中? –

相關問題