How to create an Observable from static data similar to http one in Angular?

后端 未结 5 1177
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 17:36

I am having a service that has this method:

export class TestModelService {

    public testModel: TestModel;

    constructor( @Inject(Http) public http: Ht         


        
5条回答
  •  我在风中等你
    2020-12-12 18:24

    This way you can create Observable from data, in my case I need to maintain shopping cart:

    service.ts

    export class OrderService {
        cartItems: BehaviorSubject> = new BehaviorSubject([]);
        cartItems$ = this.cartItems.asObservable();
    
        // I need to maintain cart, so add items in cart
    
        addCartData(data) {
            const currentValue = this.cartItems.value; // get current items in cart
            const updatedValue = [...currentValue, data]; // push new item in cart
    
            if(updatedValue.length) {
              this.cartItems.next(updatedValue); // notify to all subscribers
            }
          }
    }
    

    Component.ts

    export class CartViewComponent implements OnInit {
        cartProductList: any = [];
        constructor(
            private order: OrderService
        ) { }
    
        ngOnInit() {
            this.order.cartItems$.subscribe(items => {
                this.cartProductList = items;
            });
        }
    }
    

提交回复
热议问题