AngularJS 공장을 사용하여 데이터베이스의 제품 정보를 표시하는 데 문제가 있습니다. 기본적으로 하드 코딩 된 배열 대신 데이터베이스에서 제품을 표시하도록 수정 한 장바구니 응용 프로그램입니다.AngularJS 팩토리를 사용하여 데이터를 검색하는 방법은 무엇입니까?
Heres는 기본 응용 프로그램 파일의 소스 코드 (app.js) :
'use strict';
var shop = angular.module('shop', []);
// create a data service that provides a store and a shopping cart that
// will be shared by all views (instead of creating fresh ones for each view)
shop.factory("DataService",['$http', function($http) {
// create store
var myStore = new store($http);
// return data object with store and cart
return {
store: myStore
//cart: myCart ignore for now
}
}]);
// adding the config on the module
shop.config(function($routeProvider) {
$routeProvider // angular object, injected dynamically
.when('/', // we show the store on the root
{
controller: 'StoreController',
templateUrl: 'partials/store.htm'
})
.when('/cart',
{
controller: 'CartController',
templateUrl: 'partials/cart.htm'
})
.when('/checkout',
{
controller: 'CheckoutController',
templateUrl: 'partials/checkout.htm'
})
.when('/invoice',
{
controller: 'InvoiceController',
templateUrl: 'partials/invoice.htm'
})
.otherwise({ redirectTo: '/' }); // store
});
var controllers = {};
controllers.StoreController = function($scope, $routeParams, DataService) {
$scope.store = DataService.store;
console.log($scope.store);
//$scope.cart = DataService.cart;
}
상점 소스 코드 (store.js) I 데이터 검색 :
이function store($http) {
this.products = [];
this.url = 'php/db.php';
this.fields = [
'product_id',
'product_name',
'product_description',
'product_price'
];
this.products = this.getProducts($http);
}
store.prototype.getProducts = function($http) {
$http.post(this.url, { "action" : 'products', "fields" : this.fields })
.success(function(data, status) {
//$scope.result = data; // Show result from server in our <pre></pre> element
//return data;
this.products = data;
})
.error(function(data, status) {
//return data || "Request failed";
//this.status = status;
this.products = [];
});
}
store.prototype.getProduct = function (sku) {
for (var i = 0; i < this.products.length; i++) {
if (this.products[i].sku == sku)
return this.products[i];
}
return null;
}
아무도 말해 줄 수를 여기서 내가 뭘 잘못하고 있니?
- 왜 this.product 변수를 데이터베이스 결과로 설정합니까?
- 더 많은 함수를 사용하여 제품 클래스를 확장하여 항목을 데이터베이스에 저장하고 싶습니다. 어떻게 그렇게할까요?
많은 조언을드립니다.
안부
I 아래 app.js 코드를 추가
UPDATE, I 컨트롤러로 문제를 구비하고있다 (StoreController) 저장소 클래스에서 데이터를 액세스 (store.js) . 여전히 빈 배열을 보여줍니다. m.e.conroy가 제안한 코드를 변경했습니다. 당신은 당신이 그렇게 this.products
가 $http
약속을 포함하는 것, 그것이 생성 promise
을 반환하고 $http.post
을 반환 할 때
는
'use strict';
var shop = angular.module('shop', []);
shop.factory("DataService",['$http', '$q', function($http, $q) {
// create store
var myStore = new store($http, $q);
return {
store: myStore
}
}]);
// adding the config on the module
shop.config(function($routeProvider) {
$routeProvider // angular object, injected dynamically
.when('/', // we show the store on the root
{
controller: 'StoreController',
templateUrl: 'partials/store.htm'
})
.when('/cart',
{
controller: 'CartController',
templateUrl: 'partials/cart.htm'
})
.when('/checkout',
{
controller: 'CheckoutController',
templateUrl: 'partials/checkout.htm'
})
.when('/invoice',
{
controller: 'InvoiceController',
templateUrl: 'partials/invoice.htm'
})
.otherwise({ redirectTo: '/' }); // store
});
var controllers = {};
controllers.StoreController = function($scope, $http, $routeParams, DataService) {
$scope.store = DataService.store;
}
shop.controller(controllers);
이, 약속을 반환 DataService.store을 복용 컨트롤러 이전 컨트롤러 종속성 가치. 그리고 함수를 저장하면 결과 객체를 반환하지 않는 것 같습니다 ...이 객체를 반환해야합니다. 이 전체 저장소 팩토리 구현으로 깔끔한 예제를 만들 수 있습니까? –
간단한 메모리 캐시를 위해 anglejs 앱 https://github.com/andreev-artem/angular_experiments/tree/master/examples/architecture 및 여기 http://jsfiddle.net/u5gV2/의 멋진 예제를 살펴보십시오. –
반환되는 데이터는 정의되지 않습니다. 코드에서 this.products 변수를 성공 처리기에서 반환되는 변수로 설정했습니다. – QCar