Angularjs에서 $ 자원 인스턴스 URL에 액세스합니다
-
26-12-2019 - |
문제
이 코드로 자원 인스턴스를 만들었습니다.
$scope.book = Book.get({bookId:1});
.
여기에 서비스 코드가 있습니다 :
var bookServices=angular.module('bookServices',['ngResource']);
bookServices.factory('Book',['$resource',
function($resource){
return $resource('/books/:bookId',{},{});
}]);
.
도서에는 URL이 액세스 할 수있는 표지 이미지가 있습니다. /books/:bookid/cover.png
자원 인스턴스에서 URL을 가져 오는 방법은 무엇입니까?
$scope.book.$$url
.
는 정의되지 않습니다.
해결책
나는 이것이 견해 관심사이며 거기에서 처리되어야한다고 생각합니다. 나는 지금 이것을 테스트 할 수 없지만, 내 헌치는 당신의 뷰 템플릿에 URL을 빌드하는 것입니다.
그래서, 책 세부 템플릿은 다음과 같습니다 :
<div>
<p>Name: {{ book.name }}</p>
<img ng-src="/books/{{ book.id }}/cover.png" alt="cover">
</div>
.
상대 경로로 재생해야 할 수도 있지만 트릭을 수행해야합니다. 컨트롤러와 서비스를 밖으로 나가는 것을 지키고 싶어하며, 각도는 NGSRC 지침
편집
원래의 질문에 더 잘 대답하기 위해 다른 해결책이 있습니다. Decorator 패턴을 사용하여 $ Resource Service API를 확장 URL을 리소스 객체의 속성으로 노출시킵니다.
다음과 같이 $ 자원 서비스를 장식하십시오 :
function ResourceDecorator($delegate) {
var decorator = function (url, paramDefaults, actions) {
var resource = $delegate(url, paramDefaults, actions),
getSave;
// expose the parameterized url of the resource
resource.$url = url;
// expose urls for individual resources by extending
// the get method to return a class object that has
// a url property
getSave = resource.get;
resource.get = function(parameters, success, error) {
var r = getSave(parameters, success, error),
paramName;
// get the name of the parameter, assuming just ONE
paramName = Object.keys(parameters)[0];
// replace the parameter with it's value
r.$url = url.replace(':' + paramName, parameters[paramName]);
// return the decorated class object back
return r;
};
return resource;
};
return decorator;
}
app.config(['$provide', function ($provide) {
$provide.decorator('$resource', ['$delegate', ResourceDecorator]);
}]);
.
그런 다음 URL을 자원 객체의 속성으로 사용할 수 있습니다.
$scope.book.$url
.
이 간단한 예제가 지원하지 않는 $ 자원 시나리오의 전체 WACK가 있지만 개념의 증거를 보여줍니다.
이 plunker
제휴하지 않습니다 StackOverflow