Typescript - 将数据从Observable设置为属性

时间:2017-12-15 09:22:21

标签: typescript observable angularfire2 angular5

我试图从AngularFireDatabase.object()调用的Observable结果中提取数据,并将其设置为一个属性,以便稍后在其他范围内使用它。

export class QuizzEditComponent implements OnInit {
  private quizzRef: any;
  private quizzObject: any;
  private key: string;

  constructor(private router: ActivatedRoute, private database: AngularFireDatabase) {
    this.key = this.router.snapshot.paramMap.get('id');
    this.quizzRef = this.database.object(environment.firebase.databaseName+'/'+this.key);
    this.quizzRef.valueChanges().forEach(line => {
      this.quizzObject = line;
      console.log(this.quizzObject); // this display the wanted object
    });
    console.log(this.quizzObject); // This display undefined
  }
}

我尝试了不同的迭代,例如for let line of this.quizzItem没有工作,因为Observable是一个对象!

任何想法!

3 个答案:

答案 0 :(得分:1)

这只是与在组件中设置数据的方式有关的问题。从你的代码中,如果你希望得到你的observable的最后一个元素,一种方法就是设置变量后调用一个函数。这样,您可以确保在您调用的函数中未定义变量this.quizzObject

export class QuizzEditComponent implements OnInit {
  private quizzRef: any;
  private quizzObject: any;
  private key: string;

  constructor(private router: ActivatedRoute, private database: AngularFireDatabase) {
    this.key = this.router.snapshot.paramMap.get('id');
    this.quizzRef = this.database.object(environment.firebase.databaseName+'/'+this.key);
    this.quizzRef.valueChanges().forEach(line => {
      this.quizzObject = line;
      console.log(this.quizzObject); // this display the wanted object
      this.myFunction()
    });

    myFunction(){
      //do all the computation here to the last element return by the observable
      console.log(this.quizzObject); 
    }

  }
}

答案 1 :(得分:0)

使用push存储此类数据

private quizzObject=[];

而不是this.quizzObject = line;尝试this.quizzObject.push(line);

答案 2 :(得分:0)

谢谢大家,this.quizzObject它会在一段时间后填满(Async Scope),这就是第二个console.log()显示未定义的原因。

解决方案是通过空数据初始化this.quizzObject并创建一个formBuilder,然后使用(ngModel)将其管理到模板中。

组件:

init(){
  this.key = this.router.snapshot.paramMap.get('id');
  this.initObject();
  this.quizzRef = this.database.object(environment.firebase.databaseName+'/'+this.key);
  this.quizzItem = this.quizzRef.valueChanges().subscribe(item => {
    this.quizzObject = item;
  });
}

initObject(){
  this.quizzObject = [];
  this.quizzObject.question = "";
  this.quizzObject.reponses = [{1: "", 2: "", 3: "", "correctAnswer": ""}];

  this.quizzForm = this.formBuilder.group({
    question: [this.quizzObject.question, Validators.required],
    reponses: this.formBuilder.group({
      1: this.quizzObject.reponses[1],
      2: this.quizzObject.reponses[2],
      3: this.quizzObject.reponses[3],
      correctAnswer: this.quizzObject.reponses.correctAnswer
    }),
  });
}

模板:

<form [formGroup]="quizzForm" (ngSubmit)="onSubmit()" role="form">
              <div class="form-group has-success">
              <div class="card bg-light mb-3">

                  <div class="card-header">

                    <label class="form-control-label" for="question">Question</label>

                </div>
                <div class="card-body">
                    <input formControlName="question" type="text" class="form-control form-control-success" id="inputSuccess" [(ngModel)]="quizzObject.question" required>
                </div>
              </div>
        </div>

这不是最好的方法,但它解决了我的问题(y)