angularjs - 更改资源的基本 URL

标签 angularjs angular-resource

我正在使用 Angular 在同一应用程序上使用 RESTful API。我在 http://sample-site.com/api/contacts

上为 contacts 资源设置了 $resource

这很棒并且有效,但是我需要在应用程序的不同页面上与 /api/contacts 的基本 CRUD 进行交互。

例如,我需要在 http://sample-site/friends/{friend-id} 托管的网络应用程序的另一个页面上再次与联系人交互。但是,当我尝试在该页面上使用我的联系人资源时,该资源的 URL 会附加到当前 URL:

获取| http://sample-site/friends/1/api/contact

但我真正需要的是 GET |该页面上该资源的 http://sample-site/api/contact

有没有办法配置资源来定义与当前页面相关的不同基本 URL?

这是我尝试更改资源内的基本 URL:

 .factory('ContactRest', ['$resource', '$location', function($resource, $location) {
    var host = $location.host()

    return $resource('https://:url/:action', {}, {
    // Normal CRUD actions
    query: { 
        url : host,
        action : 'api/contact',
        method : 'GET',
        isArray : true,
    }
 }]);

这使得https://sample-site/friends/1/sample-site/api/contact。不管我如何定义 $resource,只是不断将任何 URL 附加到基本 URL 上。我需要更改 URL 的基础。

最佳答案

我明白了!

.factory('ContactRest', ['$resource', '$location', function($resource, $location) {
    var host = $location.host()

    return $resource('http://' + host + ':action', {}, {
    // Normal CRUD actions
    query: { 
        method : 'GET',
        isArray : true,
    }
}]);

/**
 * In controller
 */
ContactRest.query({ action: 'api/contact' }, function(contact) {
    console.log('Got it, take that Havascript!');
});

关于angularjs - 更改资源的基本 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345165/

相关文章:

mysql - 如何格式化 'time' 字段 - Angularjs 和 mySql

javascript - 如何让两个 Controller 在 Angular 中执行相同的操作,但改变网站的视觉方面?

javascript - 无法通过 $resource 获取数组

javascript - 返回对象时出现 Angular 资源错误

javascript - 工厂返回数据后未设置 Angular $scope

css - 如何更改此 ui-select 元素的样式表? ( Angular )

javascript - 带有自定义模板的 AngularJS 指令

angularjs - 如何配置 Angular $resource (ngResource) 以使用 CORS 从另一个域中提取数据

javascript - Angular UI-Grid : In a cell template, 如何从不同的字段/单元格访问值

angularjs - 渲染 404 页面而无需在 Angular js 中重定向