1

I am trying to limit users to vote only once on a `forumpost`. I have been struggling with correctly using arrays to handle this functionality in angular for a while now.

Right now my code is failing when loading all my forumposts. The error occurs when building the formgroups and when there are more than 1 userId in my upVoters: string[] so I assume my arrays are wrong. any help, tip or pointing me into the right direction is much appreciated!

my idea:

add upVoters: string[] to Forumpost class.
push userId into string[] when voting
compare if userId is already in the voters string[]
true => remove userId from array
false => add userId to array

it is working great until I start loading up the array with multiple userIds.
after investing many hrs of research on SO and other coding blogs and similiar I couldn't find an answer that was able to help me solve my problem so I decided to ask the community for help. I found a couple articles to nested FormArrays but none I could find were able to help me with my use case or maybe I do not understand how to implement correctly

Angular 2 Typescript: TypeError: this.validator is not a function

I am defining my entity and my mapping functions in my forum.service.ts file so I can use them anywhere in my application

    export class ForumPost {
      id: string;
      title: string;
      writerId: string;
      upVoters: string[];
    
      constructor() {
        this.id = '';
        this.title = '';
        this.writerId = '';
        this.upVoters = [];
      }
    }

    mapFormToForumPost(form: FormGroup): ForumPost {
        const forumPost = form.getRawValue();
        return forumPost;
    }
    
    mapForumPostToForm(forumPost: ForumPost): FormGroup {
      const form = this.formBuilder.group(forumPost);
      this.handleVotesFromForumPostForForm(form, forumPost.upVoters);
      return form;
    }


    handleVotesFromObjectToForm(form: FormGroup, arrayUpVoters: string[]) {
      form.removeControl('upVoters');
      if (arrayUpVoters && arrayUpVoters.length === 0) {
        const upVotersForForm = [];
        form.addControl('upVoters', this.formBuilder.array(upVotersForForm))
      } else {
        const upVotersForForm = [];
        for (const item of arrayUpVoters) {
          upVotersForForm.push(item);
      }
      form.addControl('upVoters', this.formBuilder.array(upVotersForForm))
    }

in my application i have a page where i use an http.get call to getAll forumposts like this. the http request is called in the ngOnInit() of the forumList.component.ts file

      forumPosts: FormGroup[] = [];
    
      constructor(private forumService: ForumService, private formBuilder: FormBuilder, private formHelper: FormHelper ) {}

      loadTopics() {
        this.forumService.getForumPosts(this.postsPerPage, this.currentPage)
          .subscribe(response => {
            for (const forumPost of response.forumPosts) {
              console.log(forumPost);
              this.forumPosts.push(this.formBuilder.group(forumPost));
              for (const post of this.forumPosts) {
                this.formHelper.disableControls(post);
              }
            }
            this.totalPosts = response.maxPosts;
          });
      }

my corresponding HTML looks like this forumList.component.html

    <mat-card class="outerCard" *ngIf="this.forumPosts.length > 0">
      <forum-list-post
       *ngFor="let forumPostForm of forumPosts | sort: 'votes'"
       [forumPostForm]="forumPostForm"
      ></forum-list-post>
    </mat-card>

following my error stacktrace with corresponding locations in my code. you can see its failing when building a formgroup via formbuilder. i have added a console log of my forumPost just before getting mapped to a formGroup.

stacktrace code location enter image description here

2
  • I'd check line 42 and 47. Commented Oct 30, 2020 at 22:23
  • 42 is only where loadtopics function is called in ngOnInit. okay i will check and compare response data to my entities. updating deleting post all worked though up until adding more userIds into the upVoters: string[] Commented Oct 30, 2020 at 22:48

1 Answer 1

0

for anyone encountering same problem here is how i resolved my problem. i decided to refactor my forum.service file by changing the mapping functions a bit. instead of using the formbuilder to build a formgroup i defined the formgroup myself inside my mapping function like this.

  mapForumPostToForm(forumPost: ForumPost): FormGroup {
    const newform = new FormGroup({
      id: new FormControl(forumPost.id),
      title: new FormControl(forumPost.title),
      writerId: new FormControl(forumPost.writerId),
      upVoters: this.formBuilder.array(forumPost.upVoters),
    });
    return newform;
  }

drawback of this is i need to add fields here when i add new variables to my forumPost entity. as it is located inside my forum.service.ts file i just need to make sure not to forget when adding new variables to my entities

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.