Consuming Json with Angularjs

Asked

Viewed 2,057 times

2

I’m trying to access a EndPoint through the Angularjs.

This is my Service:

angular.module('empresa-view')
    .factory('empresaService', ['$resource', function ($resource) {
        return $resource($SERVICES_CONTEXT + 'empresa/:params', {}, {
            update: {
                method: "PUT"
            },

            lista: {
                method: 'GET',
                params: {params: 'list'},
                isArray: true

            }

        });

    }]);

When I run the application of the following error:

GET XHR http://localhost:8080/Exemplovraptor/company [HTTP/1.1 405 Method Not Allowed 5 ms] error[Object Object] main.js:12:21 Request cross-origin blocked: The same origin policy (Same Origin Policy) prevents reading the remote resource on http://localhost:8080/Exemplovraptor/company. (Reason: the header CORS 'Access-Control-Allow-Origin' is not present).

But if I change the empresa/:params for empresa/list' works and I can display take the data. Because the params is not working?

2 answers

1

The problem is that your server needs CORS access in order to run JSON output, put this in the header of your JSON output:

header('Access-Control-Allow-Origin: *');

And for your entire application, set the useXDomain:

angular.module('empresa-view')
    .factory('empresaService', ['$resource','$httpProvider', function ($resource,$httpProvider) {
          $httpProvider.defaults.useXDomain = true;
          delete $httpProvider.defaults.headers.common['X-Requested-With'];

     var params = {'list':'list','param1':'valor_param1'} 
        return $resource($SERVICES_CONTEXT + 'empresa', params, {
            update: {
                method: "PUT"
            },
            lista: {
                method: 'GET',
                isArray: true,

            }

        });

    }]);

Here are some examples: http://notes.3kbo.com/cors

  • I already have a CORS. This is the complete endpoint: http://localhost:8080/ExemploVraptor/empresa/list o :params should receive list but does not receive. If I put the list right in place of :params works

  • From the detail of the error in your reply, it is clear that the error is server permission, if it does not work, it is probably some apache configuration that is not configured for CORS use: no .htaccess, do this: Header set Access-Control-Allow-Origin "*"

  • then it would be better if I passed the list directly instead of passing it as parameter?

  • would be asism: return $resource($SERVICES_CONTEXT + 'empresa/list', {}, {

  • If you are already passing the parameter in the json collection, you do not need to pass it in the url. Look at the answer for an example.

1


Hello.

I believe that the design of the Angularjs services fatctory is mistaken.

Here is the official documentation https://docs.angularjs.org/api/ngResource/service/$Resource

To do this as you would have to pass the :params on the service call, by exmeplo.

meuServico.$lista({params: list});

In the declaration of the service itself would be

angular.module('empresa-view')
    .factory('empresaService', ['$resource', function ($resource) {
        return $resource($SERVICES_CONTEXT + 'empresa/:params', 
        {params: list}, 
        {
            update: {
                method: "PUT"
            },

            lista: {
                method: 'GET',
                isArray: true

            }

        });

    }]);

But I see no reason to do it.

When you declare defaultParams within the service itself it passes via URI, for example http://localhost:8080/Exemplovraptor/company? params=list.

That’s why he claims cross-origin violation.

Edited

You could do the following (if you like)

angular.module('empresa-view')
        .factory('empresaService', ['$resource', function ($resource) {
            return $resource($SERVICES_CONTEXT + 'empresa/:params', 
            {params: @parametros}, 
            {
                update: {
                    method: "PUT"
                },

                lista: {
                    method: 'GET',
                    isArray: true

                }

            });

        }]);

So when you instantiate this service, you can go directly through the object property. For example

var meuServico = new empresaService();

meuServico.parametros = "list";

meuServico.$lista();

Edited to better answer query question

By default all angular services have these methods

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

When using Factory it’s like you win these free invokers. So even without declaring the query, he knows that there is a query method that is linked to being a service of type GET that expects a response ARRAY and will be asked the declared URL.

And because everything at the angle works like dependency injection, as you pass the service to your controller, you can already access it directly if you need to use the new you just use the new to assign aspects of its service to another object (prototyping).

  • I don’t understand much either, I’m following a tutorial: https://pedrohosilva.wordpress.com/2015/04/30/aplicacao-web-com-vraptor-4-pt10-3/ That’s why I’m trying to do it this way

  • @Techies see the edition I made in the post, I hope it helps you a little more.

  • I understood yes, another question. in my Controlle I do this: empresaService.query(fucntion... This is where I do the right search? But how is it connected to my service?

  • @Techies see the second edition of the post. If you answer your question.

  • Thank you, @Erick. I managed to resolve and thank you for the additional explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.