2014-11-26 4 views
2

새로운 Firebase 쿼리를 공장에서 작동 시키려고하는데, 막혔습니다. 상대방 이름을 기준으로 상대방 테이블에서 '로고'의 가치를 반환하고 싶습니다. 나는 실행 중포 기지 문서에서 console.log와 예제를 얻을 수 있습니다 : Angular factory에서 Firebase 쿼리를 사용하는 방법은 무엇입니까?

function OpponentService($firebase) { 
    var factory = {}; 
    var _url = 'https://somefirebaseproject.firebaseio.com/opponents'; 
    var _ref = new Firebase(_url); 

    factory.getLogo = function(opponent) { 
     _ref.orderByChild('name').equalTo(opponent).on("child_added", function(snapshot){ 
      console.log(snapshot.val().logo); 
     }); 
    }; 

    return factory; 
} 

내 컨트롤러 OpponentService.getLogo(opponentName) 내 공장 전화

, 내 콘솔에서 올바른 로고 ID를 얻을. 하지만 값을 내 콘솔로 보내지 않고 어떻게 반환 할 수 있습니까? 나는 이것을 다음과 같은 변수에 저장하려고한다 : $scope.opponentLogo = OpponentService.getLogo(opponentName).

factory.getLogo = function(opponent) { 
     _ref.orderByChild('name').equalTo(opponent).on("child_added", function(snapshot){ 
      return snapshot.val().logo; 
     }); 
}; 

하지만 분명히 내가 완전히 내가 undefined를 얻을 수 있기 때문에 공장, 각도에서 어떻게 작동하는지 이해가 안 :이 같은 return 문에 여러 가지 변화를 시도했다. 그 가치가 아직 사용 가능하지 않을 수 있으며 나는 언젠가 약속을 사용해야합니까? 나를 올바른 방향으로 안내 할 수있는 사람은 누구입니까?

답변

5

Firebase on() 콜의 익명 함수에서 로고 값을 반환하지만, getLogo()에서 아무것도 반환하지 않습니다.

약속을 되 돌리는 것이 좋은 방법 일 것입니다. 고유입니다

// getLogo() returns a promise that you can bind to the UI. 
// When loading finishes, the binding will get the opponent's logo value. 
factory.getLogo = function (opponentName) { 
    var opponentsArray = $firebase(_ref.orderByChild('name').equalTo(opponentName)).$asArray(); 

    // $loaded() returns a promise, so we can use the then() method to add 
    // functionality when the array finishes loading and the promise resolves. 
    var r = opponentsArray.$loaded().then(function() { 
     // Now return the logo for the first matching opponent 
     return opponentsArray[0].logo; 
    }); 

    return r; 
}; 

opponentName 경우에는 같은 opponentName을 사용할 수 있도록, 내가 데이터 구조를 재고 것 :이 보장 opponentName은 고유하지 않습니다이 경우, AngularFire와 상대 로고를 검색하는 방법입니다 상대방을위한 열쇠. 그럼 당신은 하나의 상대를 얻을 보장 할 것이며 그것을 가져올 수 :

var opponent = $firebase(_ref.child(opponentName)).$asObject(); 

당신이 AngularFire을 사용하지 않는 경우, 당신은 각도의 $q 서비스를 사용하여 약속을 반환 할 수 있습니다.

factory.getLogo = function(opponent) { 
    $q(function (resolve, reject) { 
     function successCallback(snapshot) { 
      resolve(snapshot.val().logo); 
     }; 

     function cancelCallback(error) { 
      reject(error); // pass along the error object 
     }; 

     _ref.orderByChild('name').equalTo(opponent) 
      .on("child_added", successCallback, cancelCallback); 
    }); 
}; 

당신은 범위 변수에 getLogo()의 결과를 할당 할 수 있으며, 중포 기지가 값을 반환 할 때 바인딩은 UI 업데이트됩니다 : 다음은 작동합니다.

+0

답장을 보내 주셔서 감사합니다. 이미 AngularFire를 사용하고 있으므로 쉽게 말할 수 있어야합니다. – Lennert

+0

한 명의 상대방 로고를 반환하려고합니까? 앱의 상대방의 다른 속성에 액세스하거나 바인딩해야합니까? –

+0

예이 방법에서는 한 명의 상대방 로고 만 반환하면됩니다. 그러나 전체 팩토리에는'factory.getAllOpponents'와 같은 더 많은 메소드가 포함되어 있습니다. – Lennert

관련 문제