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로 배열을 렌더링하는 방법과 내 코드가 콘솔 외부에서 작동하지 않는 이유는 무엇입니까?
Angular가 자동으로'unsubscribe()'를 처리 할 때'async' 파이프를 사용해야합니다. 옵션 1을 사용한다면'ngOnDestroy'에서'unsubscribe()'를 호출하는 것을 잊지 마십시오. –