2012-11-19 5 views
0

우리가 만들고있는 각도 앱에 매우 이상한 문제가 있습니다. 아래에 정의 된 리소스 (예 : 빌드 할 수있는 간단한 예제)에서 데이터를로드 할 때마다 데이터 바인딩 (예 : ng-repeat = '메시지를 메시지로'또는 {{message.id}}로 사용할 수있는 데이터를 다시 가져옵니다.) 그러나 나는 그것을 배열이나 객체 (gether {{id : myId}) 또는 query()를 사용하는 wether에 따라 액세스하여 javascript에서 읽지 못한다.

반복을 통해 $ get, $ query, $ save 등의 키를 얻을 수 있지만 실제 데이터는 없습니다. 문제 (A)에서

app.factory('Message', ['$resource', function($resource) { 
    return $resource('MY_URL/messages/:id', {id: '@id'}); 
}]); 

app.service('messageService', ['$rootScope', 'Message', function($rootScope, Message) { 
    var messages = Message.query(); 
    var selectedMessage = null; 

    var service = {}; 

    service.get = function(id) { 
        // Problem A (see below for details) 
     if (arguments.length === 1) return Message.get({id: id}); 
     else return messages; 
    }; 

var MenuCtrl = function($scope, Project, messageService, otherService) { 
    $scope.projects = Project.query(); 
    $scope.messages = messageService.get(); 

    // Problem B (details below) 
}; 

내가 그러나 내가 데이터가 준비되기 전에 일어날 통화를 처리 할 수있는 방법이 필요합니다, 하나의 요소가 이미 인출되었습니다 컬렉션을 형성 반환 할 수 있어야합니다.

문제 B에서 가져온 데이터 중 일부를 처리하고 "otherService"에 결과를 전달하고 싶습니다. 그러나 데이터 준비가 완료 될 때까지 지연시킬 방법이 필요합니다.

+0

다음 API docs에 따르면

: 여기

The $httpBackend used in production, always responds to requests with responses asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, follow and maintain. At the same time the testing mock, can't respond synchronously because that would change the execution of the code under test. For this reason the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests and thus preserving the async api of the backend, while allowing the test to execute synchronously.

어떤 상황과 예제 대답. 검색된 리소스를 어떻게 반복합니까? –

+0

반복은 for (each) 루프를 사용한 테스트 일뿐입니다. 그러나 나는 할 수있을 것으로 기대할 것입니다 : 경고 (메시지 [1] .id) – martijnve

+0

좋아, 여전히, 나는 당신이 동기 호출로 리소스에 대한 호출을 취급한다고 가정하고있어 정확한 코드를 볼 것이 좋습니다. 비동기입니다. 더 많은 정보는 여기에 있습니다 : http://stackoverflow.com/questions/11966252/how-does-the-resource-get-function-work-synchronously-in-angularjs/11966512#11966512 –

답변

1

이 문제는 단위 테스트에서 나타났습니다.이 문제를 해결하려면 모의 $ httpBackend를 "내 보냅니다". 그것은 조금 어렵다, 그래서 당신은 당신이 자바 스크립트에서 해당 리소스에 액세스에 대해 이동하는 방법을 보여주지 않았다

// define a resource within a service 
angular.module('app.services', ['ngResource']) 
    .factory('Message', function ($resource) { 
    var url = ... 
     , params = ... 
     , actions = ...; 

    return $resource(url, params, actions); 
    } 

// Query the resource in a controller 
function MessagesCtrl ($scope, $routeParams, Message) { 
    $scope.messages = Message.query(); 
} 

// unit test with a mocked backend 
describe('MessagesCtrl', function() { 
    var scope, ctrl, $httpBackend, messages; 

    beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) { 
    $httpBackend = _$httpBackend_; 
    scope = $rootScope.$new(); 

    messages = [ 
     { 
     id: '1', 
     text: 'foo', 
     }, { 
     id: '2', 
     text: 'foo', 
     } 
    ] 

    $httpBackend.expectGET('/api/messages').respond(messages); 
    ctrl = $controller('MessagesCtrl', {$scope: scope}); 
    })); 

    it('should get a list of messages', function() { 

    // THE NEXT LINE WILL SOLVE THE PROBLEM 
    $httpBackend.flush(); 

    expect(scope.message).toEqualData(message); 
    }); 
}); 
+0

투표가 종료 된 이유는 무엇입니까? @martijnve가 결과가 나오기 전에 비동기 호출의 결과에 접근하려고한다면, 이것은 일어날 것입니다. 나는 정확한 문제를이 문제에서 설명한 것을 보았다. 그리고 이것이 내가 어떻게 해결 했는가 ... –

+0

아스 워 (Aswer)에 감사드립니다. 약속에 관한 링크는 깨닫고 있습니다. 그러나 나는 내 unittests하지만 내 정기 컨트롤러 에이 문제가 발생하지 않습니다. 내 데이터를로드하는 즉시 js를 통해 데이터를 사용하여 작업을 수행하려고합니다. Message.get()의 결과에 다음 (myfunc (data) {...}) 호출 할 수 fugured 귀하의 링크를 기반으로하지만이 내게 오류 메시지 : "TypeError : Object # 메서드가 없습니다 ' 그때'". – martijnve

+0

@martijnve 나는 이것을 이해하는 데 도움을주고 싶지만, 당신이하려고하는 것을 정확히 볼 필요가있다. 당신은 당신의 질문에 맥락을 가지고 좀 더 자세한 예제를 게시 할 수 있습니까? –

관련 문제