Angular forEach无法读取属性

时间:2018-08-31 06:23:38

标签: angular

我正在使用Angular从url中获取JSON数据,并使用一个搜索词来过滤JSON数据并创建一个新数组,以便在HTML中查看过滤后的JSON数据。 但是,当我打开页面时,控制台会说“无法读取未定义的属性'forEach'”

这是代码:

search-result.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Observable } from "rxjs";
import { JsoncallItem } from "./../jsoncall-item";

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

    _postsArray: JsoncallItem[] = [];

    @Input() value: string;
    @Input() showthis: boolean;

    private postsURL ="http://cloudofgoods3/anguler_app_items";

  newArr: any[] = [];

  constructor(private http:HttpClient) { }

      getPosts(): void{
        this.http.get<JsoncallItem[]>(this.postsURL).
        subscribe(
            resultArray => {this._postsArray = resultArray;
          this.getResult();
       })
  }
  getResult(){
      this._postsArray.forEach(function(term){
        if(term.title == this.value){
          this.newArr.push(term.title)
        }
      }.bind(this));
  }

  ngOnInit(): void{
    this.getPosts();
  }
}

search-result.compenent.html:

<ul *ngIf="showthis">
    <li *ngFor="let item of newArr">
        Say {{item}}
    </li>
</ul>

怎么了?

2 个答案:

答案 0 :(得分:2)

这意味着您的数组为 undefined ,您在设置 _postsArray 之前正在调用该函数。您可以通过检查来修复它或初始化数组,

//Initialize as

_postsArray: JsoncallItem[] = [];

if(this._postsArray && this._postsArray.length > 0){
 this._postsArray.forEach(function(term){
        if(term.title == this.value){
          this.newArr = this.newArr + [term.title]
        }
  }.bind(this));
}

答案 1 :(得分:1)

初始化数组

_postsArray: JsoncallItem[] = [];

订阅后致电setResult,而不是onInit。

  subscribe(  resultArray =>{
          this._postsArray = resultArray;
          this.setResult();
   })