【问题标题】:Issue with forkJoin, the code does not run past subscribeforkJoin 的问题,代码不会在订阅后运行
【发布时间】:2018-07-19 10:32:41
【问题描述】:

下面的代码从数据库中获取两个值。

这是通过使用我从未使用过的forkJoin 来完成的。使用它的原因是因为我有一个函数需要在调用函数this.complexWordIdentification(this.postIWant, this.theHardWords);之前准备好两个值@

因为它在 ngOnInit 上,所以它会在开始时加载它,这正是我想要的,因为在这种情况下,我想从数据库中加载特殊单词和从数据库中加载文本,然后通过函数运行它在开始时,但该函数需要具有以下两个值: this.theHardWordsthis.PostIWant

如下图Observable.forkJoin( 中没有到达console.log('first');。谁能发现我做错了什么?谢谢!

ngOnInit() {
    this.isLoading = true;
    this.form = new FormGroup({
      annotation: new FormControl(null, {
        validators: [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(250)
        ]
      })
    });
    this.id = this.route.snapshot.paramMap.get('postId');
    this.annotationService.getWords();
    this.postsService.getPosts();

   Observable.forkJoin(
      this.annotationService.getWordUpdateListener(),
      this.postsService.getPostUpdateListener()
    ).subscribe(
      data => {
        // data[0] result from getWordUpdateListener
        this.thewords = data[0];
        this.thewords.map(word => {
          console.log('first');
          this.theHardWords.push(word.word);
          this.wordWithAnnotation.push(word);
        });
        // data[1] result from getPostUpdateListener
        this.posts.map(post => {
          console.log('second');
          if (post.id === this.id) {
            this.postIWant = post.fileText;
          }
        });
        console.log('third');
        this.isLoading = false;
        this.complexWordIdentification(this.postIWant, this.theHardWords);
      },
      err => {
        console.log(err);
        // error handling
      }
  );

    this.role = this.authService.getUserRole();
    this.userIsAuthenticated = this.authService.getIsAuth();
    this.authStatus = this.authService
      .getAuthStatus()
      .subscribe(isAuthenticated => {
        this.userIsAuthenticated = isAuthenticated;
        this.role = this.authService.getUserRole();
      });
    this.isLoading = false;
}

如果您想提出任何问题,请随时帮助回答此问题。我想补充一点,我不是太有经验...谢谢!

【问题讨论】:

  • 您是否尝试设置断点以查看它是否进入该行? this.thewords = data[0];
  • @David 是的,即使我将console.log(first); 移到this.thewords = data[0]; 上,不幸的是它仍然没有显示,知道为什么会这样吗?
  • 并非如此。在使用 forkJoin 时,您是否检查过您的任何服务是否被调用?
  • @David 你怎么检查那个对不起?在这方面没有太多经验。我可以向您展示我过去是如何编写代码的,并且一切正常,但是我不得不在外部调用该函数。这个代码是有人 forkJoin 建议的,以便在 this.postIWantthis.theHardWords 完全加载后调用该函数。
  • 例如在this.annotationService.getWordUpdateListener() 中设置断点。

标签: angular typescript rxjs observable fork-join


【解决方案1】:

尝试使用类似的东西。

forkJoin(
  this.annotationService.getWordUpdateListener(),
  this.postsService.getPostUpdateListener()
).subscribe(
  // Your code
);

检查forkJoin的rxjs documentation。 我创建了一个小例子gist.github

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2020-03-29
    • 2021-11-30
    • 2017-11-12
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多