비즈니스로직이나 화면에 보여주어야 하는 데이터가 페이지에서 페이지로 혹은 컨트롤러에서 컨트롤러로 전달될 경우 서비스를 이용해서 활용하면 편하다는걸 알았다.
컨트롤러에서 서비스의 데이터를 사용하려면 해당 데이터가 이미 초기화 완료되어 있어야 한다.
하지만 이 데이터가 http request와 같은 시간 차이가 발생하는 promise 혹은 timeout 처럼 결과가 나오는 데 시간이 소요되는 경우 어떻게 활용 할까?
Anguar JS 홈페이지에서 아래와 같은 해결 방법을 알려 준다.
resolve
- {Object.<string, function>=}
- An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. For easier access to the resolved dependencies from the template, the resolve
map will be available on the scope of the route, under$resolve
(by default) or a custom name specified by the resolveAs
property (see below). This can be particularly useful, when working with components as route templates.
Note: If your scope already contains a property with this name, it will be hidden or overwritten. Make sure, you specify an appropriate name for this property, that does not collide with other properties on the scope.
routeProvider 혹은 stateProvider 의 .config 함수 내 resolve 옵션을 이용하면, 컨트롤러가 inject 된 서비스의 promise를 기다릴 수 있도록 설정할 수 있다.
댓글 없음:
댓글 쓰기