angular - 我如何访问角度服务的数据?
问题描述
这是我的角度 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);
}
}
解决方案
上没有getItems()
方法CartService
,那么应该如何this.cartService.getItems();
工作?
您可以getItems()
在您的服务上定义:
getItems() {
return this.items;
}
或者,如果您items
是公共成员,CartService
则可以像这样访问它:items = this.cartService.items;
推荐阅读
- javascript - 如何在不冻结浏览器的情况下一次一个节点地在 ASCII 艺术网格中“动画化”变化?
- computer-vision - 关于对象的有界框
- python - 如何避免 2 个地块被错误混合?
- amazon-web-services - 如何通过 cloudformation 将值插入 dynamodb?
- java - 使用 @LoadBalanced 注释的 WebClient.Builder 时出现 WebClientResponseException$ServiceUnavailable 错误
- node.js - 导出的nodejs类中的未定义方法
- drake - PyDrake:获取反作用力和接触结果
- vb.net - 具有预定歌曲和页面转换的音频播放器。最好的语言
- javascript - 如何为我的页面提供一个不仅显示背景图像,而且填充页面其余部分的 div?
- javascript - Javascript ES6 按相同内容排序