2016-07-25 4 views
0

나는 kitem을 개인 키트로 정의했습니다 : any []; 수업에서. 그러나 this.kitems = items;를 사용하여 어떤 값도 할당 할 수 없습니다. 나는 console.log (this.kitems)를 할 때 빈 배열을 얻고있다.typescript의 다른 배열에 배열을 할당 할 수 없습니다.

createprofile() { 
    this._UserRef.on("value", function(snapshot) { 
     let items = []; 
     snapshot.forEach(function(childSnapshot) { 
      let item = childSnapshot.val(); 
      item['key'] = childSnapshot.key; 
      items.push(item); 
     }); 
     console.log(items[0].key); 
     this.kitems = items; 
    }.bind(this)); 
    console.log(this.kitems); 
} 
+0

** on ** 기능은 비동기식이며 실행하기 전에보고있는 콘솔 로그가 완료 되었기 때문에 확신합니다.:) – toskv

+0

디버깅 시도;) – toskv

답변

0

는 (귀하의 경우 on() 사용) 중포 기지 데이터베이스에 리스너를 부착 , 은 데이터베이스에서 데이터를로드하는을 시작합니다. 이 작업은 시간이 걸리기 때문에 JavaScript 코드는 계속 실행되고 코드는 빈 배열을 인쇄합니다. 그런 다음 서버에서 데이터를 사용할 수있게되면 콜백이 호출되고 배열에 데이터가 추가됩니다.

createprofile() { 
    console.log("Start listening"); 
    this._UserRef.on("value", function(snapshot) { 
     console.log("Got value"); 
     let items = []; 
     snapshot.forEach(function(childSnapshot) { 
      let item = childSnapshot.val(); 
      item['key'] = childSnapshot.key; 
      items.push(item); 
     }); 
     this.kitems = items; 
    }.bind(this)); 
    console.log("After listener"); 
} 

가 출력 될 것입니다 : 당신이 어떤 로그 문 추가 할 경우

이 따라하는 것이 가장 쉬운 방법입니다 청취자

있어 값 후

을 듣고

시작을

아마도 이것은 예상 한 것과 다를 수 있습니다. 그러나 현대 인터넷 기반 프로그래밍의 본질에 내재되어 있습니다. 대부분의 API에서 이러한 동작이 발생합니다.

소위 비동기 API를 처리 할 때 코드를 다르게 프레임하는 것이 일반적입니다. 전통적인 프로그래밍을 사용하면 "먼저 A를 얻고 B를 수행하십시오."라는 코드를 작성합니다. 비동기 API를 사용하면 "A를 얻을 때 B와 함게"로 프레임화할 수 있습니다. 데이터 서버에서 되돌아 왔다는되면 kitems에만 기록되는 것은 아닙니다

createprofile() { 
    this._UserRef.on("value", function(snapshot) { 
     let items = []; 
     snapshot.forEach(function(childSnapshot) { 
      let item = childSnapshot.val(); 
      item['key'] = childSnapshot.key; 
      items.push(item); 
     }); 
     this.kitems = items; 
     console.log(this.kitems); 
    }.bind(this)); 
} 

: 코드에서 그건 당신이에 콜백 함수를 kitems에게 를 필요로하는 코드를 이동 있다는 것을 의미한다. 더 나아가 Firebase 데이터베이스가 데이터를 동기화하므로 데이터가 변경 될 때마다 콜백이 실행됩니다..

kitem을 필요로하는 코드를 콜백에 넣으면 재사용 가능성이 손상 될 수 있으므로 콜백 함수를 데이터로드 코드에 전달하는 것이 일반적입니다. 당신이 중포 기지의 on() 함수에 전달하는 콜백 매우 유사하지만, 다음 사용 사례에 맞게 조정의

createProfileAndThen(callback) { 
    this._UserRef.on("value", function(snapshot) { 
     let items = []; 
     snapshot.forEach(function(childSnapshot) { 
      let item = childSnapshot.val(); 
      item['key'] = childSnapshot.key; 
      items.push(item); 
     }); 
     this.kitems = items; 
     callback(this.kitems); 
    }.bind(this)); 
} 

createProfileAndThen(function(kitems) { 
    console.log(kitems); 
}); 

.

0

코드에 this을 사용하고 있습니다. 대부분 this이 잘못되었을 가능성이 큽니다. 화살표 기능을 사용

createprofile =() => { 
    this._UserRef.on("value", (snapshot) => { 
     let items = []; 
     snapshot.forEach((childSnapshot) => { 
      let item = childSnapshot.val(); 
      item['key'] = childSnapshot.key; 
      items.push(item); 
     }); 
    console.log(items[0].key); 
    this.kitems = items; 
    }); 
console.log(this.kitems); 
} 

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

를 사용하지 않도록 노력 bind : https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html

+0

안녕하세요 @ basarat this.kitems = items 문 바로 뒤에 snapshot 함수 내에서 console.log를 사용하면 this.kitems 항목이 표시됩니다. 그러나 console.log (this.kitems)를 수행하면 그 함수 밖에서 빈 배열이 나타납니다. –

관련 문제