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");
}
}
是。好答案。 –
您可以重新解釋一下這個問題嗎? –
快速問題。如果DataRepository包含汽車列表。然後當它注入。你不是在調用這個'this.dataRepository.cars'的汽車列表嗎? –