Angular订阅服务:订阅不是函数

时间:2019-11-16 16:22:43

标签: angular service subscribe

我正在关注Angular官方教程,并且正在执行此步骤:https://angular.io/start/data#display-the-cart-items 它们展示了如何在组件中使用服务。

它不在本教程中,但我试图显示TopBarComponent内部购物车中的产品数量。

我的服务cart.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CartService {
  items = [];

  addToCart(product) {
    this.items.push(product);
    console.log(this.items);
  }

  getItems() {
    return this.items;
  }

  clearCart() {
    this.items = [];
    return this.items;
  }

}

我的组件top-bar.component.ts:

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

@Component({
  selector: 'app-top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.css']
})
export class TopBarComponent implements OnInit {
  public numberItems = 0;
  constructor(
    private cartService: CartService,//Inject the cart service
  ) { 

  }

  ngOnInit() {
    this.cartService.getItems.subscribe((items) => {
       this.numberItems = items.length;
       alert(this.numberItems);
    })
  }

}

我的模板top-bar.component.html

<a [routerLink]="['/']">
  <h1>My Store</h1>
</a>

<a [routerLink]="['/cart']" class="button fancy-button">
{{numberItems}}
<i class="material-icons">shopping_cart</i>Checkout</a>

我遇到一个错误:this.cartService.getItems.subscribe不是一个函数

当然,如果我在购物车中添加产品,产品的数量也不会改变。 我应该在getItems上使用Obsevable吗?

有什么想法我做错了吗?

2 个答案:

答案 0 :(得分:1)

订阅适用于可观察对象

尝试这样:

getItems(): Observable<any> {
  return of(this.items);
}

否则,

this.numberItems = this.cartService.getItems().length

答案 1 :(得分:0)

在您的服务中,您可以添加事件发射器,每次添加到购物车时,事件发射器都会发出长度。

在CartService中 这样做

import { Injectable, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class RecipesService {
  cartQty = new EventEmitter<number>();
  items = [];
  constructor() { }

 addToCart(product) {
    this.items.push(product);
    this.cartQty.emit(this.items.length);
  }

  getItems() {
    return this.items;
  }

  clearCart() {
    this.items = [];
    this.cartQty.emit(this.items.length);
    return this.items;
  }

  getCartQty() {
    return this.cartQty;
  }
}

Topbar component.ts

import { Component, Input, OnInit } from '@angular/core';
import { RecipesService } from './app.service';

@Component({
  selector: 'hello',
  template: `<h1>cart {{qty}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
  constructor(private recipesService:RecipesService) {};
  qty: number;
  @Input() name: string;

  ngOnInit() {
    this.recipesService.getCartQty().subscribe(res => {
      this.qty = res;
    })
  }
}

Working Solution