Andrew
Andrew

Reputation: 705

Issue with forkJoin, the code does not run past subscribe

The code below is fetching two values from the database.

This is getting done by using forkJoin which I have never used. The reason for using this is because I have a function which requires the two values to be ready before calling the function this.complexWordIdentification(this.postIWant, this.theHardWords);

As it is on the ngOnInit, it loads it at the start which is what I want because, in this scenario, I want to load the special words from the database and the text from the database and then run it through a function at the start but that function needs to have those two values which are: this.theHardWords and this.PostIWant.

As shown below in the Observable.forkJoin( it does not get to the console.log('first');. Can anyone spot what I am doing wrong? Thanks!

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;
}

If you wish to ask any questions feel free to do so to help answer this question. I would like to add that I am not too experienced...Thanks!

Upvotes: 0

Views: 179

Answers (1)

MichaelKie
MichaelKie

Reputation: 146

Try using something like this.

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

Check the rxjs documentation of forkJoin. I've created a small example gist.github.

Upvotes: 1

Related Questions