0

I am sticking with $http and $resource because i am not able to get it when we need to use $resource in angular application ? But, i have one confusion reguaring when we already use $http then what is main purpose of behind $resource use in own application ?

VjyV
  • 344
  • 2
  • 13

2 Answers2

0

The way i look at $resource, is pre-define $http calls.

If you using the same call all over your application, it is easy to just inject the $resource service and make the call

Another advantage of $resouce if the api url change you only have to change in one place.

Valter
  • 2,859
  • 5
  • 30
  • 51
  • yes, agree with you but we can also make it using $http use throughout application same url – VjyV Oct 10 '16 at 06:40
0

A big advantage I see in $resource over $http is the modelling of your datas. If you're passing around a Resource object named Student and your perform

var Student = $resource('/api/student/:id');
Student.get({id: 123}, student => {
    student.testScorePerc = 98;
    student.$save();
}); 

You expect to receive an object representing a Student with the last name of "LastName". That is far cleaner, in my opinion, than making use of a service that is dependent on $http like so...

Service.$inject = ['$http'];
function Service($http) {
    this.getStudent = function(id) {
        $http({method: 'GET', url: `api/student/${id}` });
    };
    this.updateStudent = function(id, student) {
        $http({method: 'PUT', url: `api/student/${id}`, data: student});
    };
}
Service.getStudent(123).then( res => {
    let student = res.data[0];
    student.testScorePerc = 98;
    Service.updateStudent(student.id, student).then( res => {
        let dosomethngWith = res.data;
    }).catch( err => {
        console.log(err);
    });
});

I think it becomes far less clear when using the service... and of course this is a simple example.

Baseline for me is that I get to interact with Resource objects that, in my opinion, are cleaner and more representative of my data.

nham
  • 161
  • 5
  • Thanks for help but can you say me 'let' means ? how can we use it ? – VjyV Oct 10 '16 at 06:42
  • This stack overflow article should answer your questions about let. It is a scoped variable in javascript meaning. That means that any variable that was defined with a let will only be available in the closure in which it was defined. http://stackoverflow.com/questions/762011/let-keyword-vs-var-keyword-in-javascript – nham Oct 10 '16 at 12:49