2016-10-13 3 views
4

저는 AngularFire2와 함께 Firebase에서 3 개의 변수 (배열)를 채우려고합니다.Angular2의 .map/.subscribe는 어떻게 작동합니까?

DB 구조는 이것이다 : 나는 그 변수를 채우기 위해 매핑 약속을 해결하는 방법에 붙어

Firebase3 structure

. 가장 쉬운 쿼리조차도 아무 것도 반환하지 않으며 console.log에도 아무 것도 표시되지 않습니다.

let testConnection = this.AngularFire.database.list(DbPath) 
      .map((items) => { 
      console.log(items); 
      return items.map(item => { 
       console.log(items); 
       console.log(item); 
    })}) 

나는 .subscribe로했지만,이 스냅 샷을 보존하기 때문에 (그리고 그것이 작동하지 않는 보존하지 않고), 나를 위해 해 드리겠습니다 아니다 : /. 하지만 제대로 작동하고 채웠습니다.

return this.AngularFire.database.list(DbPath, { preserveSnapshot: true }) 
.subscribe(
(snapshots:any) => { 
    snapshots.forEach(snapshot => { 
    console.log(snapshot.key); 

     if (snapshot.key === 'disliked') { 
     this.dataListDisliked = snapshot.val(); 
    } 
    ... 

아이디어가 있으십니까? 고마워요

+1

지도는 내가 해결 출력 형식을 사용, 약속이 해결 된 후에 호출됩니다 :

이 앱이 모습입니다. E.G 구문 분석 및 http 응답 및 반환 json. map이 호출 된 후 observable에 가입 ​​한 사람은 새로운 값 ("mapped"값)을 알게된다. 맵과 서브 클래스를 모두 수행하고 싶다면 – bassxzero

+0

https://angular.io/docs/ts/latest/tutorial/toh-pt6에서 'app/hero-search.service.ts'를 확인하십시오.html – bassxzero

답변

9

정확하게 이해할 수 있는지 모르겠으므로 질문에 답변 할 수 있기를 바랍니다.

그래서이 코드 조각 :

let testConnection = this.AngularFire.database.list(DbPath) 
    .map((items) => { //first map 
    console.log(items); 
    return items.map(item => { //second map 
     console.log(items); 
     console.log(item); 
    }) 
    }) 

내가 당신을 위해 그것을 무너 뜨리는 시도거야는 각도 중포 기지는 목록 개체를 만들 때 그래서는 관찰 가능한 반환, 관찰 가능한을 사용합니다. 따라서 첫 번째 맵은 관측 가능 함수의 함수이므로 관측 값이 값을 방출 할 때마다 함수를 맵핑 할 수 있습니다. 기본적으로 첫 번째지도는 목록이 변경 될 때마다 실행됩니다.

<FirebaseListObservable<any>> af.database.list('Todos').map(items 
:

import { Component } from '@angular/core'; 
import { AngularFire, FirebaseListObservable } from 'angularfire2'; 
import 'rxjs/add/operator/map'; // you might need to import this, or not depends on your setup 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    title = 'app works!'; 
    text = ''; 
    todos: FirebaseListObservable<any[]>; 
    constructor(af: AngularFire) { 
    this.todos = <FirebaseListObservable<any>> af.database.list('Todos').map(items => { //first map 
      return items.map(item => { //second map 
      item.text = item.text.toUpperCase(); 
      return item; 
      }) 
     }); 
    } 

    addTodo() { 
    this.todos.push({ 
     text: this.text, 
     completed: false 
    }); 
    this.text = ''; 
    } 

    changeTodo(key: string, completed){ 
    this.todos.update(key, {completed: !completed}); 
    } 
} 

코드는, 혼동 될 수있는 유일한 것은이 줄 매우 간단하다 : enter image description here

이제 이것은 매우 간단한 응용 프로그램 구성 요소는 다음과 같습니다 왜 그렇게이 목록 봐 그것이 당신이 우리의 응용 프로그램을 실행하면

당신은 지금이 answer

에서 그것에 대해 자세한 내용을보실 수 있습니다 아무 일도 일어나지 않습니다. 아무것도 콘솔에 로그인 할 수 없습니다. 왜? 아무 것도 우리의 Todos가 관찰 할 수있는 것을 구독하지 않았기 때문입니다. 우리는 어떻게 구독하나요? 경우,

this.todos.subscribe(todos => { 
    //now we can assign our todos to a variable 
    this.ourTodoList = todos; 
}); 

내가이 매우 기본적인 도도 앱 간단한 Github repo을 만들어 :

<li *ngFor="let todo of todos | async" [ngClass]="{completed: todo.completed}" (click)="changeTodo(todo.$key, todo.completed)"> 
    {{ todo.text }} 
    </li> 

또는 우리의 구성 요소에 대한 우리의 관찰 가능한 수동 가입 : 우리는 우리의 견해에 비동기 파이프를 사용하는 두 가지 방법이 복제 할 수 있고, Firebase 데이터베이스 (모든 지시 사항은 README 파일에 있음)를 가리키고 로컬 머신에서 실행할 수 있습니다. enter image description here

+0

굉장한 노력, 나에게 설명해 주셔서 고마워요 –

+0

광범위한 설명 ...하지만 그들은 무엇을합니까? 명확한 상처가 필요합니다. –