首页 > 解决方案 > 我如何访问角度服务的数据?

问题描述

这是我的角度 service.ts 代码

 import { Injectable } from '@angular/core';
    
    export interface Item{
      id : number;
      title: string;
      price: number;
      category: string;
    }
    
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class CartService {
    
      cartItems : Item[] = [];
    
      constructor() { }
    
      addToCart(products: any[]) {
        this.cartItems.push(products[0]);
      }

     getItems() {
     return this.cartItems;
     }
    }

这是从 home.components.ts 传递给 addToCart() 函数 products[] 的数据的代码结构

products =[{id1:this.id, title1:this.title,price1:this.price,category1:this.category}];

我如何从另一个组件访问这些数据。我尝试如下,但它不工作。

import { Component, Input, OnInit } from '@angular/core';
import { CartService } from '../cart.service';
@Component({
  selector: 'app-mycart',
  templateUrl: './mycart.component.html',
  styleUrls: ['./mycart.component.css']
})
export class MycartComponent implements OnInit {

  constructor(private cartService: CartService) { }
  items = this.cartService.getItems();
  ngOnInit(): void {
    alert(this.items[0].title);
  }
}

标签: angulartypescript

解决方案


上没有getItems()方法CartService,那么应该如何this.cartService.getItems();工作?

您可以getItems()在您的服务上定义:

getItems() {
 return this.items;
}

或者,如果您items是公共成员,CartService则可以像这样访问它:items = this.cartService.items;


推荐阅读