2017-07-10 37 views
0

我是Aurelia的新手。我正在瀏覽一些例子並看到了這個例子。 它有這個頁面列出cars.js)所有的汽車,並具有創建按鈕將您重定向到不同的頁面,在這裏你可以輸入一個新的汽車(addCar.js),一旦你點擊保存,你會被重定向到汽車名單。夠簡單。使用存儲庫將對象推入陣列

我的問題是,新增加的汽車如何被推到汽車名單?本示例使用存儲庫將所有交互抽象爲api。這些文件是否共享this.cars的相同實例?

dataRepository.js

@inject(HttpClient) 
export class DataRepository { 
    constructor(httpClient) { 
     this.httpClient = httpClient; 
    } 

getCars() { 
    var promise = new Promise((resolve, reject) => { 
     if (!this.cars) { 
      this.httpClient.fetch('api/Cars') 
      .then(response => response.json()) 
      .then(data => { 
       this.cars = data; 
       resolve(this.cars); 
      }).catch(err => reject(err)); 
     } 
     else 
      resolve(this.cars); 
    }); 
    return promise; 
} 

    addCar(car) { 
     var promise = new Promise((resolve, reject) => { 
      this.httpClient.fetch('api/Cars',{ 
       method: 'POST', 
       body: json(car) 
      }).then(response => response.json()) 
      .then(data => { 
       this.cars.push(data); // <-- here, how does this pass the related data to cars.js? 
       resolve(data); 
      }).catch(err=>reject(err)); 
     }); 
     return promise; 
    } 
} 

addCar.js

@inject(DataRepository) 
export class AddCar { 
    constructor(dataRepository) { 
     this.car = { carType: "Big" }; 
     this.dataRepository = dataRepository; 
    } 

    activate(params, routeConfig, navigationInstruction) { 
     this.router = navigationInstruction.router; 
    } 

    save() { 
     this.validation.validate().then(()=>{ 
      this.dataRepository.addCar(this.car).then(car=> this.router.navigateToRoute('cars')); 
     }); 
    } 
} 

cars.js

@inject(DataRepository) 
export class Cars { 
    constructor(dataRepository) { 
     this.dataRepository = dataRepository; 
    } 

    activate(params, routeConfig, navigationInstruction) { 
     this.cars = []; 
     this.router = navigationInstruction.router; 
     return this.dataRepository.getCars().then(cars => { 
      this.cars = cars; 
     }); 
    } 

    addCar() { 
     this.router.navigateToRoute("addCar"); 
    } 
} 

回答

2

沒有硝酸鉀關於Aurelia的具體細節,我會假設它使用單實例依賴注入(因此@inject指令)。該實例具有汽車的集合,並且在傳遞給該依賴的構造函數時被設置爲實例成員。更多信息可以發現here

+0

是。好答案。 –

+0

您可以重新解釋一下這個問題嗎? –

+0

快速問題。如果DataRepository包含汽車列表。然後當它注入。你不是在調用這個'this.dataRepository.cars'的汽車列表嗎? –