TypeError:无法读取未定义Angular的属性'indexOf'

时间:2018-05-09 13:21:18

标签: angular mean

我正在制作一个MEAN堆栈应用,我收到了这个错误:

TypeError: Cannot read property 'indexOf' of undefined.

问题似乎在于这一行:

<div *ngIf="newComment.indexOf(product._id) > -1">

我将newComment定义为组件中的变量,如下所示:

newComment = [];`

所以应该定义它。有谁可以提供帮助吗?

修改

按要求提供enire文件。

product.component.html(div在最后)

<h1 class="pb-2 mt-4 mb-2 border-bottom">Producten</h1>

<div class="row show-hide-message" *ngIf="message && newProduct">
  <div [ngClass]="messageClass">
    {{ message }}
  </div>
</div>

<button type="button" name="button" class="btn btn-warning" *ngIf="!newProduct" (click)="newProductForm()">Nieuwe productvraag</button>
<button [disabled]="loading" type="button" name="button" class="btn btn-default" *ngIf="!newProduct" (click)="reload()"><i class="fas fa-sync-alt"></i>&nbsp;&nbsp;Reload</button>
<div><br></div>

<form [formGroup]="form" name="productForm" (submit)="onProductSubmit()" *ngIf="newProduct">
    <div class="form-group">
        <label for="title">Titel</label>
        <div>
          <input type="text" name="title" class="form-control" placeholder="*Product Titel" autocomplete="off" formControlName="title" />
          <ul class="help-block text-danger" *ngIf='form.get("title").touched'>
            <li *ngIf='form.get("title").errors?.required'>Dit veld is verplicht</li>
            <li *ngIf='form.get("title").errors?.minlength || form.get("title").errors?.maxlength'>Max lengte: 50, Min lengte: 2</li>
            <li *ngIf='form.get("title").errors?.alphaNumericValidation'>Mag enkel letters of nummers bevatten</li>
          </ul>
        </div>
      </div>

      <div class="form-group">
        <label for="body">Vraag</label>
        <div>
          <textarea name="body" rows="8" cols="80" placeholder="*Beschrijving" class="form-control" formControlName="body"></textarea>
          <ul class="help-block text-danger" *ngIf='form.get("body").touched'>
            <li *ngIf='form.get("body").errors?.required'>Dit veld is verplicht</li>
            <li *ngIf='form.get("body").errors?.minlength || form.get("body").errors?.maxlength'>Max lengte: 500, Min lengte: 5</li>
          </ul>
        </div>
      </div>

      <button [disabled]="processing" type="button" name="button" (click)="goBack()" class="btn btn-warning">Terug</button>
      <button [disabled]="processing || !form.valid" type="submit" name="button" class="btn btn-success">Plaats</button>
</form>

<div *ngIf="!newProduct">
  <div *ngFor="let product of producten">
    <div class="card">
      <div class="card-header">
        <h3>{{ product.title }}</h3>
      </div>
      <div class="card-body">
        <p class="card-text">
            {{ product.body }}
        </p>
      </div>
      <div class="card-footer">
          <strong>Gepost door: </strong> {{ product.createdBy }}
          <br>
          <strong>Datum: </strong> {{ product.createdAt | date:'dd-MM-yyyy' }}
          <br>
          <div *ngIf="username === product.createdBy">
              <strong>Likes: </strong>{{ product.likes }}
          </div>
          <br>
          <a [routerLink]="['/bewerkProduct/', product._id]" *ngIf="username === product.createdBy"><button type="button" name="button" class="btn btn-sm btn-info">Bewerken</button></a>
          <a [routerLink]="['/verwijderProduct/', product._id]" *ngIf="username === product.createdBy"><button type="button" name="button" class="btn btn-sm btn-danger">Verwijderen</button></a>
          <div class="dropdown">
            <button type="button" name="button" class="btn btn-sm btn-success" *ngIf="username !== product.createdBy" (click)="likeProduct(product._id)">
                <i class="fas fa-thumbs-up"></i>&nbsp;&nbsp;{{ product.likes }}
            </button>
            <div class="dropdown-content">
              <a href="#">Jana</a><br>
              <a href="#">Evelyn</a><br>
              <a href="#">Noelle</a><br>
            </div>
          </div>
      </div>

      <ul class="list-group">
        <li class="list-group-item">
          <button [disabled]="newComment.indexOf(product._id) > -1" type="button" name="button" class="btn btn-sm btn-danger" (click)="comment(product._id)">Comment</button><br>
          <div *ngIf="newComment.indexOf(product._id) > -1">
            <form [formGroup]="commentForm">
                <textarea name="comment" rows="10" cols="30" class="form-control" formControlName="comment"></textarea>
                <div [ngClass]="">
                    <ul class="help-block text-danger" *ngIf='commentForm.get("comment").touched'>
                        <li *ngIf='commentForm.get("comment").errors?.required'>Dit veld is verplicht</li>
                        <li *ngIf='commentForm.get("comment").errors?.minlength || form.get("title").errors?.maxlength'>Max lengte: 200, Min lengte: 1</li>
                    </ul>
                </div>

                <button [disabled]="!commentForm.valid || processing" type="submit" name="button" class="btn btn-sm btn-info" (click)="postComment(product._id)">Plaats comment</button>
                <button [disabled]="processing" type="button" name="button" class="btn btn-sm btn-danger" (click)="cancelSubmission(product._id)">Cancel</button>
              </form>
          </div>
          <li *ngIf="enableComments.indexOf(product._id) === -1 && product.comments.length > 0" class="list-group-item">
            <span (click)="expand(product._id)">Toon comments&nbsp;&nbsp;
                <i class="fas fa-comment"></i>
            </span>
          </li>
          <li *ngIf="enableComments.indexOf(product._id) > -1" class="list-group-item">
            <span (click)="collapse(product._id)">Verberg comments&nbsp;&nbsp;
                <i class="fas fa-comment-slash"></i>
            </span>
          </li>
          <div *ngIf="enabledComments.indexOf(product._id) > -1">
            <li *ngFor="let comment of blog.comments" class="list-group-item">
              <strong>{{ comment.commentator }}: </strong> {{ comment.comment}}
            </li>
          </div>
        <!-- </li> -->
      </ul>
    </div>
    <br>
  </div>
</div>

product.compontent.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { ProductService } from '../../services/product.service';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  messageClass;
  message;
  newProduct = false;
  loading = false;
  form;
  processing;
  username;
  producten;
  newComment = [];
  commentForm;
  enabledComments = [];

  constructor(
    private formBuilder: FormBuilder,
    private authService: AuthService,
    private productService: ProductService
  ) {
    this.createNewProductForm();
    this.createCommentForm();
   }

  createNewProductForm() {
    this.form = this.formBuilder.group({
      title: ['', Validators.compose([
        Validators.required,
        Validators.maxLength(50),
        Validators.minLength(2),
        this.alphaNumericValidation
      ])],
      body: ['', Validators.compose([
        Validators.required,
        Validators.maxLength(500),
        Validators.minLength(5)
      ])]
    });
  }

  createCommentForm() {
    console.log(this.newComment);
    this.commentForm = this.formBuilder.group({
      comment: ['', Validators.compose([
        Validators.required,
        Validators.minLength(1),
        Validators.maxLength(200)
      ])]
    });
  }

  disableFormNewProductForm() {
    this.form.get('title').disable();
    this.form.get('body').disable();
  }

  enableFormNewProductForm() {
    this.form.get('title').enable();
    this.form.get('body').enable();
  }

  enableCommentForm() {
    this.commentForm.get('comment').enable();
  }

  disableCommentForm() {
    this.commentForm.get('comment').disable();
  }

  alphaNumericValidation(controls) {
    const regExp = new RegExp(/^[a-zA-Z0-9 ]+$/);
    if (regExp.test(controls.value)) {
      return null;
    } else {
      return { 'alphaNumericValidation': true};
    }
  }

  newProductForm() {
    this.newProduct = true;
    this.createNewProductForm();
  }

  reload() {
    this.loading = true;
    // Get producten
    this.getAllProducts();
    setTimeout(() => {
      this.loading = false;
    }, 4000);
  }

  comment(id) {
    this.newComment = [];
    this.newComment.push(id);
  }

  cancelSubmission(id) {
    const index = this.newComment.indexOf(id);
    this.newComment.splice(index, 1);
    this.commentForm.reset();
    this.enableCommentForm();
    this.processing = false;
  }

  onProductSubmit() {
    this.processing = true;
    this.disableFormNewProductForm();

    const product = {
      title: this.form.get('title').value,
      body: this.form.get('body').value,
      createdBy: this.username
    };

    this.productService.newProduct(product).subscribe(data => {
      if (!data.succes) {
        this.messageClass = 'alert alert-danger';
        this.message = data.message;
        this.processing = false;
        this.enableFormNewProductForm();
      } else {
        this.messageClass = 'alert alert-success';
        this.message = data.message;
        this.getAllProducts();
        setTimeout(() => {
          this.newProduct = false;
          this.processing = false;
          this.message = false;
          this.form.reset();
          this.enableFormNewProductForm();
        }, 2000);
      }
    });
  }

  goBack() {
    window.location.reload();
  }

  getAllProducts() {
    this.productService.getAllProducts().subscribe(data => {
      this.producten = data.producten;
    });
  }

  likeProduct(id) {
    this.productService.likeProduct(id).subscribe(data => {
      console.log(data);
      this.getAllProducts();
    });
  }

  postComment(id) {

  }

  expand(id) {
    this.enabledComments.push(id);
  }

  collapse(id) {
    const index = this.enabledComments.indexOf(id);
    this.enabledComments.splice(index, 1);
  }

  ngOnInit() {
    this.authService.getProfile().subscribe(profile => {
      this.username = profile.user.username;
    });
    this.getAllProducts();
  }

}

3 个答案:

答案 0 :(得分:4)

问题不是newComment,而是enableComments

你有两行:

<li *ngIf="enableComments.indexOf(product._id) === -1>

但它应该是enabledComments。缺少'd'

答案 1 :(得分:0)

以下是避免此错误的诀窍------&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;

class IteratorQuerySet:
    def __init__(self, qs):
        self._qs = qs

    def __iter__(self):
        return self._qs.iterator()

    def __getitem__(self, *args, **kwargs):
        return self._qs.__getitem__(*args, **kwargs)

    def __getattr__(self, attr):
        return getattr(self._qs, attr)

只需在HTML中更改此单行。

答案 2 :(得分:0)

你能告诉我完整的代码吗? 和 你也可以这样做

<强> {{'myrule'.indexOf(data.skuCode)>-1?"hello":"No"}}

或者也是 取一个新的空白列表,然后在for循环中,如果条件满足,则将其推送到空白列表 newComment = []; skuCode = “你好”;

 for(let i=0;i< this.data.length;i++){
    if(skuCode.indexOf(data[i])>-1){
       newComment.push(data[i]);
   }
}

for(let i=0;i< this.data.length;i++){
        if(data[i].indexOf(skuCode)>-1){
           newComment.push(data[i]);
       }
    }