programing

서버에서 데이터를 가져오는 권장 방법

golfzon 2023. 3. 25. 12:06
반응형

서버에서 데이터를 가져오는 권장 방법

Angular에서 서버 데이터 소스에 연결하는 권장 방법은 무엇입니까?사용하지 않는 JS$resource.

$resource에는 다음과 같은 많은 제한이 있습니다.

  1. 적절한 미래를 사용하지 않음
  2. 유연성이 부족하다

백엔드와 통신할 때 $리소스가 적절하지 않을 수 있습니다.리소스를 사용하지 않고 $resource와 같은 동작을 설정하는 방법을 보여 줍니다.

angular.module('myApp').factory('Book', function($http) {
  // Book is a class which we can use for retrieving and 
  // updating data on the server
  var Book = function(data) {
    angular.extend(this, data);
  }

  // a static method to retrieve Book by ID
  Book.get = function(id) {
    return $http.get('/Book/' + id).then(function(response) {
      return new Book(response.data);
    });
  };

  // an instance method to create a new Book
  Book.prototype.create = function() {
    var book = this;
    return $http.post('/Book/', book).then(function(response) {
      book.id = response.data.id;
      return book;
    });
  }

  return Book;
});

다음으로 컨트롤러 내에서 다음을 수행할 수 있습니다.

var AppController = function(Book) {
  // to create a Book
  var book = new Book();
  book.name = 'AngularJS in nutshell';
  book.create();

  // to retrieve a book
  var bookPromise = Book.get(123);
  bookPromise.then(function(b) {
    book = b;
  });
};

$리소스 사용을 권장합니다.

Angularjs의 다음 버전에서 지원(url override)할 수 있습니다.그러면 다음과 같이 코드화할 수 있습니다.

// need to register as a serviceName
$resource('/user/:userId', {userId:'@id'}, {
    'customActionName':    {
        url:'/user/someURI'
        method:'GET',
        params: {
            param1: '....',
            param2: '....',
        }
    },
     ....
});

리턴 콜백은 다음과 같이 ctrl 범위에서 처리할 수 있습니다.

// ctrl scope
serviceName.customActionName ({
    paramName:'param',
    ...
}, 
function (resp) {
    //handle return callback
}, 
function (error) {
    //handler error callback
});

아마도 당신은 더 높은 추상화 수준에서 코드를 다룰 수 있을 것입니다.

언급URL : https://stackoverflow.com/questions/11850025/recommended-way-of-getting-data-from-the-server

반응형