2017-04-25 4 views
2

제품 이름을 찾고 결과로 제품 카드를 출력하는 검색 상자를 만들려고합니다. 검색 입력이있는 MenuComponent가 있고 데이터베이스의 제품을 찾습니다. (이것은 300ms 동안 유지되므로 각 키 스트로크에 대한 요청을 할 필요가 없습니다). getLikeName()은 이름을 검색 한 제품을 반환합니다.* ngFor 검색 결과 업데이트되지 않는 각도 2

search(searchInput: string){ 
    if(this.interval != null){ 
     clearInterval(this.interval); 
    } 
    this.interval = setTimeout(() => { 
     this.productHttpService.getLikeName(searchInput, 20).subscribe(
     (products: any[]) => this.productContainer.displayProducts(products) 
    ); 
    }, 300); 
    } 

displayProducts 함수는 제품 목록을 업데이트합니다. 나는 console.logged 결과를 가지고 효과적으로 제품이 돌아오고있다. 그러나 목록은 웹 사이트에서 업데이트되지 않습니다.

<md-grid-list cols="4" rowHeight="1:2" class="size"> 
    <md-grid-tile *ngFor="let product of products" class="separation"> 
     <md-card class="example-card"> 
     <md-card-header> 
      <div md-card-avatar class="example-header-image"></div> 
      <md-card-title>${{product.price}}</md-card-title> 
      <md-card-subtitle>{{product.name}}</md-card-subtitle> 
     </md-card-header> 
     <img md-card-image [src]="product.imgUrl" style="width:300px; height:225px"> 
     <md-card-content> 
      <p> 
      {{product.description}} 
      </p> 
     </md-card-content> 
     <md-card-actions> 
      <button md-button (click)="sidenav.open(); addToCart(product)">ADD TO CART</button> 
     </md-card-actions> 
     </md-card> 
    </md-grid-tile> 
    </md-grid-list> 

이 답변에 미리 감사합니다
products: any[]; 

displayProducts(products: any[]){ 
    this.products = products; 
    console.log(products); 
} 

(나는 각도 재료를 사용하고 있습니다) HTML 파일입니다.

+0

보기에 바인딩 제품 [] 만 사용해 보았습니까? –

+0

그냥 권장 사항 - setInterval을 사용하는 대신 rxjs에서 debounceTime 연산자를 사용할 수 있습니다. –

답변

0

예제 코드에서 'products'변수의 범위는 'this.productContainer'로 제한되며 'this'가 아닌 것으로 보입니다. 따라서 업데이트되는 것은 HTML에 바인딩 된 '제품'변수가 아닙니다.

console.log는 displayProducts() 메소드 내부에서 인쇄 할 때 계속 작동합니다.

코드를 제공하는 것이 더 쉬울 수 있습니다.

표시 방법이 표시 이외의 아무것도하지 않는 경우, 당신이 다음에 코드를 변경 제안 : 제품이 productContainer.products에있는 것처럼

this.interval = setTimeout(() => { 
    this.productHttpService.getLikeName(searchInput, 20).subscribe(
    (products: any[]) => {this.products = products}); 
}, 300); 
0

것 같습니다. . 범위를 html 내부에서 사용할 수 있으므로 html을 *ngFor="let product of productContainer.products"으로 변경하십시오.

관련 문제