类型“Observable<{}>"上不存在属性“update".Firebase 5 AngularFire2 5 [英] Property 'update' does not exist on type 'Observable<{}>'. Firebase 5 AngularFire2 5
问题描述
我正在尝试在 firebase 中创建/更新购物车.我使用的服务具有将 localStorage ID 添加到 firebase 的功能,如果产品已经存在,它会添加购物车中的数量,否则它会创建新的.错误发生在控制台 TypeError: Cannot read property 'quantity' of null 并且我在购物车 service.ts 中编译时也出错:
- Observable<{}>"类型上不存在属性update".
- 类型{}"上不存在属性数量"
下图展示了我试图在 firebase 中获得的内容:
shopping-cart.service.ts
import { take } from 'rxjs/operators';从 'angularfire2/database' 导入 { AngularFireDatabase, snapshotChanges };从'@angular/core'导入{可注射};从'./models/product'导入{产品};@Injectable({提供在:'根'})导出类 ShoppingCartService {构造函数(私有数据库:AngularFireDatabase){}私人创建(){console.log('购物服务')return this.db.list('/shopping-carts').push({日期创建:新日期().getTime()});}私人getCart(cartId:字符串){return this.db.object('/shoping-carts/'+cartId);}私有异步 getOrCreateCartId(){让cartId = localStorage.getItem('cartId');如果(cartId)返回cartId;让结果 = 等待 this.create();localStorage.setItem('cartId', result.key);返回结果.key;}private getItem(cartId: string, productId: string){return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();}异步 addToCart(产品:产品){让cartId = await this.getOrCreateCartId();让 item$ = this.getItem(cartId, product.key);item$.pipe(take(1)).subscribe( item => {item$.update({ 产品:产品,数量:(item.quantity || 0) + 1});});}
shoppng-cart.service.ts(文档的相关部分)
private getItem(cartId: string, productId: string){return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();}异步 addToCart(产品:产品){让cartId = await this.getOrCreateCartId();让 item$ = this.getItem(cartId, product.key);item$.pipe(take(1)).subscribe( item => {item$.update({ 产品:产品,数量:(item.quantity || 0) + 1});});}
product-card.component.ts
import { ShoppingCartService } from './../shopping-cart.service';从'./../models/product'导入{产品};import { Component, OnInit, Input } from '@angular/core';@成分({选择器:'产品卡',templateUrl: './product-card.component.html',styleUrls: ['./product-card.component.css']})导出类 ProductCardComponent 实现 OnInit {@Input('product') 产品;@Input('show-actions') showActions = true;构造函数(私人购物车服务:ShoppingCartService){}添加到购物车(产品:产品){this.cartService.addToCart(product);}ngOnInit() {}}
product-card.component.html
<img class="card-img-top" [src]="product.imageUrl" *ngIf="product.imageUrl" alt="{{ product.title }}"><div class="card-body pb-0"><h5 class="card-title">{{product.title}}</h5><p>{{product.price |货币:'美元'}}</p><div class="card-footer p-0 border-top"><button *ngIf="showActions" (click)="addToCart(product)" class="btn btn-primary btn-block">加入购物车</button>
product.ts:
导出接口产品{键:字符串;标题:字符串;价格:数量;类别:字符串;imageUrl:字符串;}
经过大量搜索和调试也是 Yevgen answer 我已经修改了我的代码以摆脱错误类型错误:无法读取空值的属性数量".如果我使用 valueChanges
它会在添加新购物车时出错.所以我改为 snapshotChanges
并添加一些它存在的逻辑并且现在工作正常.如果有人仍然更新我的答案,欢迎您.
private getItem(cartId:string, productId:string) {返回 this.db.object <任何 >('/shopping-carts/' + cartId + '/items/' + productId);}异步 addToCart(product:Product) {让cartId = await this.getOrCreateCartId();让 item$ = this.getItem(cartId, product.key);item$.snapshotChanges().pipe(take(1)).subscribe((item:any) => {if (item.key != null) {item$.update( {quantity:( item.payload.val().quantity || 0) + 1});}别的{item$.set({产品:产品,数量:1});}});}
I am trying to create/update shopping-cart in firebase. I am using a service that has functions that add the localStorage ID to firebase and It add's the quantity in shopping-cart if the product already exist otherwise it created new one. The error occurred in console TypeError: Cannot read property 'quantity' of null and I also got error on compilation in shopping-cart service.ts:
- Property 'update' does not exist on type 'Observable<{}>'.
- Property 'quantity' does not exist on type '{}'
The following image demonstrate what I'm trying to get in firebase:
shopping-cart.service.ts
import { take } from 'rxjs/operators';
import { AngularFireDatabase, snapshotChanges } from 'angularfire2/database';
import { Injectable } from '@angular/core';
import { Product } from './models/product';
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) { }
private create(){
console.log('shoping service')
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string){
return this.db.object('/shoping-carts/'+ cartId);
}
private async getOrCreateCartId(){
let cartId = localStorage.getItem('cartId');
if(cartId) return cartId;
let result = await this.create();
localStorage.setItem('cartId', result.key);
return result.key;
}
private getItem(cartId: string, productId: string){
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();
}
async addToCart(product: Product){
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.pipe(take(1)).subscribe( item => {
item$.update({ product: product, quantity: (item.quantity || 0) + 1});
});
}
shoppng-cart.service.ts (relevant part of document)
private getItem(cartId: string, productId: string){
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId).valueChanges();
}
async addToCart(product: Product){
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.pipe(take(1)).subscribe( item => {
item$.update({ product: product, quantity: (item.quantity || 0) + 1});
});
}
product-card.component.ts
import { ShoppingCartService } from './../shopping-cart.service';
import { Product } from './../models/product';
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent implements OnInit {
@Input('product') product;
@Input('show-actions') showActions = true;
constructor(private cartService:ShoppingCartService) { }
addToCart(product:Product){
this.cartService.addToCart(product);
}
ngOnInit() {
}
}
product-card.component.html
<div *ngIf="product.title" class="card m-auto">
<img class="card-img-top" [src]="product.imageUrl" *ngIf="product.imageUrl" alt="{{ product.title }}">
<div class="card-body pb-0">
<h5 class="card-title">{{product.title}}</h5>
<p>{{product.price | currency: 'USD'}}</p>
</div>
<div class="card-footer p-0 border-top">
<button *ngIf="showActions" (click)="addToCart(product)" class="btn btn-primary btn-block">Add to Cart</button>
</div>
</div>
product.ts:
export interface Product{
key: string;
title: string;
price: number;
category: string;
imageUrl: string;
}
After lot of searching and debugging also part of Yevgen answer I have modified my code to get rid of ERROR TypeError: Cannot read property 'quantity' of null. If I use valueChanges
it makes error on new cart addition. So I changed to snapshotChanges
and put some logic of it's existence and working fine now. If someone still update my answer your're most welcome.
private getItem(cartId:string, productId:string) {
return this.db.object < any > ('/shopping-carts/' + cartId + '/items/' + productId);
}
async addToCart(product:Product) {
let cartId = await this.getOrCreateCartId();
let item$ = this.getItem(cartId, product.key);
item$.snapshotChanges().pipe(take(1)).subscribe((item:any) => {
if (item.key != null) {
item$.update( {quantity:( item.payload.val().quantity || 0) + 1});
}
else{
item$.set( {product:product, quantity:1});
}
});
}
这篇关于类型“Observable<{}>"上不存在属性“update".Firebase 5 AngularFire2 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!