【问题标题】:Returning data from Observables in Angular从 Angular 中的 Observables 返回数据
【发布时间】:2020-03-05 00:46:48
【问题描述】:

我正在尝试使用来自 Firestore 的数据执行操作。我正在使用 valuechanges() 订阅一个 observable 并尝试提取一个对象数组,以便我可以基于它创建一个表单。

这是我第二次使用 rxjs,我已经尝试了我所知道的一切,但无法实现。我可以在订阅中 console.log 我想要的数组,但不能返回它,所以我可以在外面使用它。

这是ts

export class ExerciseTestsComponent implements OnInit {
  exercises: Observable<any>
  exerciseForm: FormGroup;
  isAnswered: boolean; 
  isCorrect: boolean; 
  helloThere: []


  constructor(
    private fb: FormBuilder,
    private db: AngularFirestore) {}

  ngOnInit(): void {
    let exerciseTest; 
    this.db
    .collection('availableExercises')
    // .doc("xvXCAxUrj4842ItZCyrv")
    // .collection("questions")
    .valueChanges()
    .subscribe(
      res => {
        console.log(res);   
      }
      )
    console.log("below is exerciseTest ")
    console.log(exerciseTest)
    this.createGroup()
  }

  createGroup() {
    console.log("below is my firestore data")
    console.log(this.exercises)
    this.exerciseForm = this.fb.group({});
    this.exercises[0]
    .doc("xvXCAxUrj4842ItZCyrv")
    .collection("questions")
    .forEach(control =>
      this.exerciseForm.addControl(control.prefix, this.fb.control(""))
    );
  }

【问题讨论】:

  • 不能从并发操作中返回!您要么有一个回调,要么设置一个从订阅内部设置的全局变量。在此处阅读有关异步性质的更多信息stackoverflow.com/questions/14220321/…

标签: angular rxjs


【解决方案1】:

这个问题有点令人困惑。我认为您混淆了异步性质。

在您使用 ngonInit() 时,您调用 createGroup 作为常规方法的一部分,而不是作为结果处理程序的一部分。

  ngOnInit(): void {
    let exerciseTest; 
    this.db
    .collection('availableExercises')
    .valueChanges()
    .subscribe(
      res => {
        console.log(res);   
        // saving the response to a component local variable
        this.exercises = res;
        // I am calling this.createGroup() inside the result handler; not outside of it. 
       // I'm also passing in the response.
       this.createGroup()
      }
      )
  }

现在,您的创建组函数应该可以访问 this.exercises。

在您的原始实现中,this.createGroup() 很可能在结果处理程序运行之前被调用;因此 this.exercises 将是未定义的。但是,很难说,因为在您的原始代码中没有定义或赋予值 this.exercises

【讨论】:

    猜你喜欢
    • 2017-02-23
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2018-01-20
    相关资源
    最近更新 更多