简体   繁体   English

类型“ {}”上不存在属性“更新”和“数量”

[英]Property 'update' and 'quantity' doesn't exist on type '{ }'

I'm watching the tutorial of Mosh Hamedani using the Angular version 6 but the problem is the tutorial version is 4. I'm working on the e-commerce project on AddToCart button where the product should increase it's quantity by clicking the button and updated in Firebase using productId and also if I try to add new product then id of that new product should add in AngularFire Database. 我正在使用Angular版本6观看Mosh Hamedani的教程,但问题是该教程的版本是4。我正在使用AddToCart按钮进行电子商务项目,该产品应通过单击按钮来增加数量,并进行更新在Firebase中使用productId,并且如果我尝试添加新产品,则该新产品的ID也应添加到AngularFire数据库中。 I've error in the last line of item.update() and item.quantity. 我在item.update()和item.quantity的最后一行有错误。 Please go through the code and suggest me better solution. 请仔细阅读代码,并向我提出更好的解决方案。 Thanks in advance 提前致谢

Here is the code. 这是代码。

shopping-cart.service.ts shopping-cart.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from '../model/product';
import { take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db: AngularFireDatabase, ) { }

  private create() {
   return this.db.list('/shopping-cart').push({
      dateCreated: new Date().getTime()
    })
  }

  private getCart(cartId: String) {
    return this.db.object('/shopping-cart/' + cartId);
  }

  private getItem(cartId:string, productId: String) {
   return this.db.object('/shopping-cart/' + cartId + '/items/' +productId);
  }

 private async getOrCreateCart() {
    let cartId = localStorage.getItem('cartId');

    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;  
  }

  async addToCart(product: Product) {
    let cartId = await this.getOrCreateCart();
    let item$ = this.getItem(cartId, product.key);

    item$.valueChanges().pipe(take(1)).subscribe(item => {
      // I'am getting error in update() and quantity
      item.update({ product: product,quantity: (item.quantity || 0) + 1});
    })
  }
}

Expected results are that after clicking on Add To cart button, the product quantity must be updated in firebase 预期结果是,单击“添加到购物车”按钮后,必须在Firebase中更新产品数量

Have a look at my other files(for reference) 1. home.component.html (Here is the button when clicked goes to .ts file as shown below) 看看我的其他文件(供参考)1. home.component.html(单击该按钮即会转到.ts文件,如下所示)

<div class="card-footer">
    <button (click)="addToCart(product)" style="background: #2980b9; 
             color:white" class="btn btn-block">Add to Cart
    </button>
</div>
  1. home.component.ts (the click event defined here) home.component.ts(此处定义的click事件)
addToCart(product:Product) {
     this.cartService.addToCart(product);
   }

and the last file 3. shopping-cart.service.ts 最后一个文件3. shopping-cart.service.ts

private async getOrCreateCart() {
    let cartId = localStorage.getItem('cartId');

    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;  
  }

  async addToCart(product: Product) {
    let cartId = await this.getOrCreateCart();
    let item$ = this.getItem(cartId, product.key);

    item$.valueChanges().pipe(take(1)).subscribe(item => {
      item$.update({ product: product,quantity: (item.quantity || 0) + 1});
    })
  } 

Here are the error images: 1. The error is back 这里是错误图像:1.错误又回来了 类型{}上不存在属性数量 2. Now when I modify the above code of addToCart(product: Product) which is as: 2.现在,当我修改上述addToCart(product:Product)的代码时,它是:

async addToCart(product: Product) {
    let cartId = await this.getOrCreateCart();
    let item$ = this.getItem(cartId, product.key);

    item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
      if(item.key != null) {
        item$.update({ product: product,quantity: (item.quantity || 0) + 1});
      } else {
        item$.set( {product:product, quantity:1});
     }   
    });
  }

I get following error: 我收到以下错误: 项目编译成功,但是单击按钮后未定义键

This is all I have... Please see the errors again and suggest a better solution... Thanks in advance 这就是我所拥有的全部...请再次查看错误并提出更好的解决方案...在此先感谢

You use the update method on the value you get from the database. 您对从数据库获得的值使用更新方法。 You have to use the update method on a database object. 您必须在数据库对象上使用update方法。

https://github.com/angular/angularfire2/blob/master/docs/rtdb/objects.md https://github.com/angular/angularfire2/blob/master/docs/rtdb/objects.md

I could not test it, let me know if it works. 我无法测试它,让我知道它是否有效。

async addToCart(product: Product) {
    let cartId = await this.getOrCreateCart();
    let itemRef = this.getItem(cartId, product.key);

    itemRef.valueChanges().pipe(take(1)).subscribe(item => {
      itemRef.update({ product: product,quantity: (item.quantity || 0) + 1});
    })
 }

Is your products.component.ts file looking like this? 您的products.component.ts文件看起来像这样吗?

products.component.ts products.component.ts

import { ShoppingCartService } from './../shopping-cart.service';
import { Product } from './../models/product';
import { ActivatedRoute } from '@angular/router';

import { ProductService } from './../product.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { switchMap } from 'rxjs/operators';
import { Subscription } from 'rxjs';
@Component({
    selector: 'app-products',
    templateUrl: './products.component.html',
    styleUrls: [ './products.component.css' ]
})
export class ProductsComponent implements OnInit, OnDestroy {
    products: Product[] = [];
    filteredProducts: Product[] = [];
    category: string;
    cart: any;
    subscription: Subscription;
    constructor(
        route: ActivatedRoute,
        productService: ProductService,
        private shoppingCartService: ShoppingCartService
    ) 
    {
        productService
            .getAll()
            .pipe(
                switchMap((products: Product[]) => {
                    this.products = products;
                    return route.queryParamMap;
                })
            )
            .subscribe((params) => {
                this.category = params.get('category');

                this.filteredProducts = this.category
                    ? this.products.filter((p) => p.category === this.category)
                    : this.products;
            });
    }

    async ngOnInit() {
        this.subscription = (await this.shoppingCartService.getCart())
            .valueChanges()
            .subscribe((cart) => (this.cart = cart));
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Here look at the ngOnInit() function. 在这里查看ngOnInit()函数。 Before .subscribe() you have to write .valueChanges() 在.subscribe()之前,您必须编写.valueChanges()

That means you have to write 这意味着你必须写

async ngOnInit() {
    this.subscription = (await this.shoppingCartService.getCart())
        .valueChanges()
        .subscribe((cart) => (this.cart = cart));
}

shopping-cart.service.ts shopping-cart.service.ts

async addToCart(product: Product) {
    let cartId = await this.getOrCreateCart();
    let item$ = this.getItem(cartId, product.key);
    item$.snapshotChanges().pipe(take(1)).subscribe((item) => {
        if (item.payload.exists()) {
            item$.update({ quantity: item.payload.exportVal().quantity + 1 });
        } else {
            item$.set({ product: product, quantity: 1 });
        }
    });
}

I think it will work. 我认为它将起作用。 Please inform me it works or not. 请通知我它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM