programing

Angular에서의 서비스 콜 상대 경로 사용JS

linuxpc 2023. 3. 17. 19:39
반응형

Angular에서의 서비스 콜 상대 경로 사용JS

테스트 서버에 도입할 때까지 정상적으로 동작하고 있던 코드는 다음과 같습니다.

$scope.getUserList = function (userName) {
    $http({
        method: "get",
        url: "GetUserList",
        params: { userName: userName }
    }).
        success(function (data) {
            $scope.users = data;
        }).
        error(function () {
            alert("Error getting users.");

문제는 가상 디렉토리에 전개하고 있는데 다음 콜이 서버 루트에서 GetUserList를 히트하려고 한다는 것입니다.이건 말이 돼, 난 그걸 고칠 수 있는 여러 가지 방법을 알고 있어.

제가 알고 싶은 것은 Angular에서 휴대성과 유지보수가 가능한 방법으로 서비스 URL을 참조하는 올바른 방법입니다.

머리에 HTML 베이스 태그를 사용하여 모든 경로를 코드화하는 것이 좋습니다.ASP에서.예를 들어 NET은 사이트의 루트 경로일 수도 있고 아닐 수도 있으므로 기본 태그를 사용하면 도움이 됩니다.보너스: 다른 모든 자산에도 사용할 수 있습니다.

다음과 같은 기본 경로를 가질 수 있습니다.

<base href="/application_root/" />

..."foo/bar.dlinks"와 같은 링크는 실제로 /application_root/foo/bar.dlinks가 됩니다.

제가 사용하는 또 다른 접근법은 헤더에 이름 있는 링크를 넣는 것입니다.API 루트를 한 곳에 두고 디렉티브템플릿 루트를 다른 곳에 두는 경우가 많습니다.머리에는 다음과 같은 태그를 추가합니다.

<link id="linkApiRoot" href="/application_root/api/"/>
<link id="linkTemplateRoot" href="/application_root/Content/Templates/"/>

...모듈에서 $120을 사용하여 링크 href를 취득하여 다음과 같은 서비스와 디렉티브에 공개합니다.

angular.module("app.services", [])
    .config(["$provide", function ($provide) {
        $provide.value("apiRoot", $("#linkApiRoot").attr("href"));
    }]);

...다음과 같은 서비스에 주입합니다.

angular.module("app.services").factory("myAdminSvc", ["apiRoot", function (apiRoot) {
    var apiAdminRoot = apiRoot + "admin/";
    ...

제 의견일 뿐이에요.애플리케이션에 대해 가장 간단한 작업을 수행합니다.

어플리케이션을 전달할 수 있는 글로벌Configuration을 포함하는 모듈을 정의할 것을 권장합니다.

// Module specific configuration
angular.module('app.config')
  .value('app.config', {
    basePath: '/' // Set your base path here
  });

그러면 Angular 덕분에 애플리케이션 내 어디에서나 액세스할 수 있습니다.JS 종속성 주입:

// Make sure your config is included in your module
angular.module('app', ['app.config']);

// Access your config e.g. in a controller
angular.module('app')
  .controller('TestCtrl', ['$scope','app.config', function($scope, config){

    // Use config base path to assemble url
    $scope.url = config.basePath + 'GetUserList';
    ...
  }]);

베이스 패스가 변경될 때마다(예를 들어 다른 서버나 호스트로 변경할 때) 글로벌 구성에서 변경하면 됩니다.

사용할 수 없었습니다.<base>다른 원본에서 동적으로 팝업으로 응용 프로그램이 생성되었기 때문에 태그가 지정되었습니다.basePath 변수와 같은 것을 사용하여 이 스레드의 others 옵션을 검토하고 있습니다.$http, ng-src, templateUrl기타

하지만 그건 좀 오버헤드였고, xhr이 만들어지기 전에 모든 URL을 변경하는 인터셉터를 만들었다.

var app = angular.module("myApp", []);

app.config(["$httpProvider", function($httpProvider) {
    $httpProvider.interceptors.push('middleware');
}]);

app.factory('middleware', function() {
    return {
        request: function(config) {
            // need more controlling when there is more than 1 domain involved
            config.url = "//example.com/api/" + config.url
            return config;
        }
    };
});

app.controller("Ctrl", ["$http", function($http) {
    $http.get("books"); // actually requestUrl = http://example.com/api/books
}])

또한 html도

<div ng-include src="'view'">
    <!-- actually src = http://example.com/api/view -->
</div>

단, 이 제품을 사용하는 것을 추천합니다.<base>windowtag()를 한 합니다.

$location 、 、 、 、 、 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $.필요한 건 다!전화는 다음과 같습니다.$location.path()+"/GetUserList"뭐 비슷한 거.

여기를 참조해 주세요.http://docs.angularjs.org/guide/dev_guide.services.$location

MVC 페이지에서 코드 한 줄만으로 해결되는 비슷한 문제가 있었습니다.

<base href="~/" />

받아들여진 대답이 내게 도움이 되었다.Angular에서 제공하는 MVC 앱을 사용하고 있습니다.baseUrl을 각도 컨트롤러 내에서 웹 API 호출 또는 템플릿에 액세스하기 위해 사용할 수 있도록 한 단계를 더 밟았습니다.

ng-init을 사용하여 baseUrl 설정(서버 측에서 입력된 값에서)

<html ng-app="app" ng-controller="AppController">
<head>
    <base href="{{baseUrl}}" ng-init="baseUrl = '@Model.BaseUrl'" />
</head>

각도 제어기

    $scope.manageCustomerGroups = function () {
        openDialog($scope.baseUrl + 'content/templates/customerGroups.html');
    }

간단하게 말하면 ASP를 사용하고 있습니다.NET Razor(Web MVC)로 어플리케이션 패스를 취득하여 앱 베이스로 합니다.

<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Title</title>

<meta name="description" content="">
@{ var appPath = Request.ApplicationPath.ToString();
    if (!appPath.EndsWith("/")) {
        appPath = appPath + "/";
    }
}
<base href="@appPath" />

저는 모든 URL을 상대적으로 만들 것입니다.

url: "../GetUserList",

대신

url: "GetUserList",

:<base href="/application_root/" />이 환경을 환경으로 변경해야 할 수도 있고 가상 디렉토리 이름에 종속되어 있기 때문에 좋은 생각이 아닌 것 같습니다.

ng-init 함수에서는 가상 디렉토리(int ASP)의 값을 포함하는 파라미터를 전달합니다.요청에 저장된 NET입니다.Application Path).

<div ng-controller="ControllerName" ng-init="init('@Request.ApplicationPath')">

각도 컨트롤러 내에서 이 값을 모든 http 콜의 URL 프리픽스로 사용합니다.이 기능을 사용하여 경로를 결합할 수 있습니다.

function combinePath(path1, path2) {
    if (path1 == null) {
        return path2;
    }
    var last = path1.slice(-1);
    var first = path2.charAt(0);

    if (last == '/' && first == '/') {
        path1 = path1.substring(0, path1.length - 1);
    }
    return path1 + path2;
}

언급URL : https://stackoverflow.com/questions/17011616/using-a-relative-path-for-a-service-call-in-angularjs

반응형