2013-10-24 2 views
0

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); 
+0

이, 약속을 반환 DataService.store을 복용 컨트롤러 이전 컨트롤러 종속성 가치. 그리고 함수를 저장하면 결과 객체를 반환하지 않는 것 같습니다 ...이 객체를 반환해야합니다. 이 전체 저장소 팩토리 구현으로 깔끔한 예제를 만들 수 있습니까? –

+0

간단한 메모리 캐시를 위해 anglejs 앱 https://github.com/andreev-artem/angular_experiments/tree/master/examples/architecture 및 여기 http://jsfiddle.net/u5gV2/의 멋진 예제를 살펴보십시오. –

+0

반환되는 데이터는 정의되지 않습니다. 코드에서 this.products 변수를 성공 처리기에서 반환되는 변수로 설정했습니다. – QCar

답변

1
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) { 
    return $http.post(this.url, { 
     "action": 'products', 
     "fields": this.fields 
    }) 
    .success(function (data, status) { 
     return data; 
    }) 
    .error(function (data, status) { 
     return []; 
    }); 
} 

app.js. 서버에서 호출이 반환되면 success 또는 error 함수에 의해 약속을 확인하는 함수는 해당 함수에서 데이터를 반환하는 함수가 반환 할 값으로 변수 this.products을 설정합니다.

이 경우 에서 즉시 대체하려고합니다. 문제가 발생하기 전에 응용 프로그램에서 해당 데이터에 액세스하려고하면 시도한 결과 문제가 될 수있는 약속이 취소됩니다. 그것은 당신이 필요로하는 배열을 포함하고있는 것처럼 다른 기능을합니다. 당신은 $q.when을 사용하여 해결할 약속을 "대기"한 다음 반환 된 데이터를 할당 할 수 있습니다. 따라서 this.products을 다른 곳에 사용하려고하면 여전히 빈 배열이 포함되어 있으므로 this.products.length 같은 코드는 오류를 발생시키는 대신 계속 작동합니다 . 그래서 당신은 다음을 수행 할 수 있습니다 :

function store($http,$q) { 
    this.products = []; 
    this.url = 'php/db.php'; 
    this.fields = ['product_id', 'product_name', 'product_description', 'product_price']; 
    $q.when(this.getProducts($http)).then(function(data){ this.products = data; }); 
} 

당신은 당신이 당신의 서비스에 $q를 주입 한 후 클래스를 작성하는 동안 귀하의 new 연산자를 통해에 통과해야합니다 있다는 사실을,이 경로를 이동하기로 결정합니다. 이렇게하면 컨트롤러에있을 수있는 모든 경쟁 상황이 해결됩니다.

은 물론 당신은 또한 해결하기 위해 $routeProvider.when 방법에 대해 제공되는 resolve를 사용할 수있다 "컨트롤"당신이 잡을 해결해야하므로

+0

답변을 주셔서 감사합니다. 코드를 변경하고 내 컨트롤러로 질문을 업데이트했습니다. 조금만 더 방향을 알려주세요. 감사! – QCar

+0

'store.js'도'$ q'에 추가 했습니까? –

+0

예, function store ($ http, $ q) {... – QCar

관련 문제