簡體   English   中英

在Angular2視圖中渲染動態數組

[英]Render dynamic array in the view Angular2

我有一個動態數組,我希望在組件的視圖中呈現內部添加/刪除一些項目。

該數組由我的App Component(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"
    });

  }

}

我的App Component(html)中的數組的“視圖”

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

我的CartService

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);
   }
}

所以我想知道如何在Component html中渲染數組以及為什么我的代碼在控制台之外無效?

更新:

正如@TuongLe在評論中所說,如果您手動訂閱您的o​​bservable,那么您應該在ngOnDestroy調用unsubscribe以防止內存泄漏。

你也可以

1)設置數組值:

cartItems: any[];

cartSubscription: Subscription;

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

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

視圖

*ngFor="let item of cartItems"

要么

2)使用async管道如:

*ngFor="let item of cartService.cart$ | async"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM