繁体   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