How do I get an ID that is part of a URL, in angularjs? I am using Restangular to communicate with REST API's

前提是你 提交于 2019-12-11 03:52:39

问题


I am using Restangular to make backend calls and everything works fine as long as URL gives me data like below:

If I hit http://mysite/responses/ the responses look like

[
    {"fname":"some guy",
     "lname":"some name",
     "dob":2091,
     "job":"mgr",
     "id":"100"
     },
     {"fname":"another guy",
     "lname":"anpther name",
     "dob":1991,
     "job":"worker",
     "id":"101"
     },
     {"fname":"someone",
     "lname":"some name",
     "dob":1997,
     "job":"dev",
     "id":"102"
     },
     {"fname":"some guy2",
     "lname":"some name",
     "dob":2091,
     "job":"sec",
     "id":"103"
     }
] 

and everything works fine

which is wrapped in an array and my Restangular URL looks like

RestangularProvider.setBaseUrl('http://mysite/responses/');
RestangularProvider.setRestangularFields({ id: 'id' });

and it works all fine

Now I deconstructed the backend and API returns the data in below format

http://mysite/responses/100

{
    fname:"some guy",
     lname:"some name",
     dob:2091,
     job:"mgr",
     id:"100"
}

http://mysite/responses/101

{
    fname:"another guy",
     lname:"another name",
     dob:1991,
     job:"sec",
     id:"101"
}

http://mysite/responses/102

{
    fname:"some name",
     lname:"some person",
     dob:1091,
     job:"sec",
     id:"102"
}

http://mysite/responses/103

{
    fname:"a guy",
     lname:"person name",
     dob:1998,
     job:"dev",
     id:"103"
}

Now if I hit

http://mysite/responses/

I get below responses

http://mysite/responses/100
http://mysite/responses/101
http://mysite/responses/102
http://mysite/responses/103
http://mysite/responses/104

As you see, the id is getting appended to the url, and I need to get this id, make an Restangular call and get the data. How can I loop through this multiple http calls, get the id and put it in Angular. I think I am not constructing the BaseURl for Restanglar properly, because I am not sure how to get the id. thanks for the help


回答1:


What you are looking for is routeParams:

https://docs.angularjs.org/api/ngRoute/service/$routeParams

This is used together with routes:

https://docs.angularjs.org/api/ngRoute/service/$route

For example:

$routeProvider.when('/Book/:bookId', {
    templateUrl: 'book.html',
    controller: function($scope, $routeParams) {
        console.log($routeParams.bookId);
    })
});


来源:https://stackoverflow.com/questions/26976537/how-do-i-get-an-id-that-is-part-of-a-url-in-angularjs-i-am-using-restangular-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!