javascript - 如何调用函数类javascript
问题描述
我想创建一个带有私有参数和函数的类来访问我想要的数据。你可以看到这个:
export class Product {
private name: string;
private type: string;
private longDetail: string;
private shortDetail: string;
private stock: number;
private price: number;
private linkImage: string;
private id: number;
constructor(
name: string,
type: string,
longDetail: string,
shortDetail: string,
stock: number,
price: number,
linkImage: string,
id: number
) {
this.name = name;
this.type = type;
this.longDetail = longDetail;
this.shortDetail = shortDetail;
this.stock = stock;
this.price = price;
this.linkImage = linkImage;
this.id = id;
}
getName(): string {
return this.name;
}
getType(): string {
return this.type;
}
getLongDetail(): string {
return this.longDetail;
}
getShortDetail(): string {
return this.shortDetail;
}
getStock(): number {
return this.stock;
}
getPrice(): number {
return this.price;
}
getLinkImage(): string {
return this.linkImage;
}
getId(): number {
return this.id;
}
}
当我想调用组件中的函数时,我被告知:
ProductListComponent.html:15 错误类型错误:newProduct.getName 不是函数
你有解决方案吗 ?非常感谢您提前!
编辑 :
这是前端点击后调用的代码
addProductBasket(newProduct: Product) {
const newClientBasket = this.createNewClientBasketWithAdd(
this.clientBasket.getValue(),
newProduct
)
this.clientBasket.next(newClientBasket)
console.log(newClientBasket)
}
private createNewClientBasketWithAdd(
oldClientBasket: BasketProduct[],
newProduct: Product
): BasketProduct[] {
const found = oldClientBasket.find((product) => {
if (product.getId() === newProduct.getId()) {
product.addOneProduct()
}
})
if (found === undefined) {
console.log(newProduct.getName())
oldClientBasket.push(
new BasketProduct(
newProduct.getName(),
newProduct.getType(),
newProduct.getLongDetail(),
newProduct.getShortDetail(),
newProduct.getStock(),
newProduct.getPrice(),
newProduct.getLinkImage(),
newProduct.getId()
)
)
}
return oldClientBasket
}
获取数据是我的 apiservice
export class ApiService {
private dataApi: BehaviorSubject<Product[]> = new BehaviorSubject<Product[]>([]);
constructor(private http: HttpClient) {
this.getDataFromApi();
}
private getDataFromApi(){
this.http
.get<Product[]>("../../assets/data.json")
.toPromise()
.then((data) => this.dataApi.next(data));
}
public getData():Observable<Product[]>{
return this.dataApi.asObservable();
}
}
解决方案
Product
在访问其方法之前,您应该有一个类的实例。
var newProduct = new Product();
newProduct.getName();
推荐阅读
- flutter - 如何将带有数据的数组转换为小部件
- html - 在 Angular(Flexbox)下使用“行”和“列”会在 HTML 输入字段之间创建大量垂直空间
- vba - 访问应用程序从任务栏按钮双击全屏
- c++ - 为什么指针在 C++ 中不归类为实体?
- matlab - 在聚类MATLAB中计算真阳性、真阴性、假阳性和假阴性
- javascript - 如何解析 json 值(Javascript Ajax)
- jenkins - 在 Jenkins Unix slave 中触发 ALM 测试集(UFT 测试)
- python - GroupBy 应用 Python Pandas 的更快方法?
- atom-editor - 我是 atom (atom.io) 的新手,我已经下载了它,并且成功安装了它。但是如何打开这个编辑器呢?
- php - 无法使用php和sql更新数据库中的id值