2017-02-05 1 views
0

내부에 항목을 추가/제거 할 때 구성 요소의 뷰에서 렌더링 할 동적 배열이 있습니다.뷰의 동적 배열 렌더링 Angular2

어레이가 제 애플리케이션 컴포넌트 (TS)에 ngOnInit() 법에 의해 렌더링 :

import { Component, OnInit } from '@angular/core'; 
import { CartService } from './cart/cart.service'; 

import '../style/app.scss'; 

@Component({ 
    selector: 'my-app', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'], 
}) 
export class AppComponent { 
    cartItems: any; 
    image: any; 
    item: any; 

    constructor(public cartService: CartService) { } 

    ngOnInit(){ 
    this.cartService.cart$.subscribe((val) => { 
     console.log(this.cartService.cartArr)//console shows the array properly, but nothing is shown in the view if I remove "console.log" 
    }); 

    } 

} 

애플리케이션 구성 (HTML) 내부 배열 "보기" :

<ul class="cart"> 
    <li class="cart__item" *ngFor="let item of cartArr"> 
     ... 
    </li> 
</ul> 

카트 서비스 :

import { Injectable } from '@angular/core'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 


@Injectable() 
export class CartService { 
    public cart$ = new BehaviorSubject(null); 
    public cartArr = []; 

    constructor(){ } 

    public addToCart(prod) { 
     this.cartArr.push(prod); 
     this.cart$.next(this.cartArr); 
    } 
} 

그래서 컴포넌트 html로 배열을 렌더링하는 방법과 내 코드가 콘솔 외부에서 작동하지 않는 이유는 무엇입니까?

답변

2

는 업데이트 : 수동 다음은 메모리 누수를 방지하기 위해 ngOnDestroyunsubscribe를 호출해야합니다 귀하의 관찰에 가입 할 경우

으로

코멘트에 @TuongLe 말했다.

사용자 수 중

1) 집합 배열 값 :

,726 :

*ngFor="let item of cartItems" 

또는

2) async 파이프처럼 사용

cartItems: any[]; 

cartSubscription: Subscription; 

ngOnInit() { 
    this.cartSubscription = this.cartService.cart$.subscribe((val) => { 
    this.cartItems = val; 
    }); 
} 

ngOnDestroy() { 
    this.cartSubscription.unsubscribe(); 
} 

보기

+2

Angular가 자동으로'unsubscribe()'를 처리 할 때'async' 파이프를 사용해야합니다. 옵션 1을 사용한다면'ngOnDestroy'에서'unsubscribe()'를 호출하는 것을 잊지 마십시오. –