Закидание данных в json с html
Есть корзина, в которой есть две части, первая- товары (products), вторая - форма с input, после нажатия на кнопку, с формы считываются данные в json отлично, а вот товары не добавляются (назвал немного криво - user - это данные, что введены с инпутов). Скину на всякий случай почти весь код корзины, код именно с считыванием данных находится внизу кода (с приставкой orders). Дали совет, что можно попробовать так как ниже, но не получается.
data = {
userData: UserData,
products: Array<Product>
}
Буду очень благодарен за подсказки и помощь.
basket.components.ts
import { Component, OnInit, OnDestroy, Output, EventEmitter, Input } from '@angular/core';
import { BasketService } from 'src/app/core/services/basket/basket.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { UserInterface } from 'src/app/core/interfaces/user/user.interface';
import { ProductInterface } from 'src/app/core/interfaces';
@Component({
selector: 'app-basket',
templateUrl: './basket.component.html',
styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit, OnDestroy {
@Input() user: UserInterface;
@Output() newOrder = new EventEmitter<UserInterface>();
@Output() update = new EventEmitter<UserInterface>();
basketList;
product = [];
basket;
productIndex: number;
id: number;
userList: Array<UserInterface>;
productList: Array<ProductInterface>;
private unsubscribe = new Subject();
constructor(
private basketService: BasketService
) { }
ngOnInit(): void {
this.getBasketList();
this.getOrders();
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
clearBasket(): void {
localStorage.clear()
this.product = []
}
getBasketList(): void {
this.basketService.basket.pipe(takeUntil(this.unsubscribe))
.subscribe(
data => {
this.product = data;
}),
error => {
console.log(error)
};
}
deleteBasketItem(productId: number) {
this.basketService.removeFromLocalstorage(productId);
var index = this.product.findIndex(x => x.id == productId);
this.product.splice(index, 1);
}
submit(user: UserInterface): void {}
getOrders(): void {
this.basketService.getOrders()
.subscribe(data => {
this.userList = data
}),
error => console.log(error)
};
// getOrderItem(): void {
// this.basketService.getOrderItem()
// .subscribe(data => {
// this.productList = data
// }),
// error => console.log(error)
// }
updateOrders(user: UserInterface): void {
this.basketService.updateOrders(user)
.subscribe();
}
addOrder(user: UserInterface): void {
this.basketService.addOrder(user)
.subscribe(() => {
this.getOrders();
// this.getOrderItem();
});
}
//get total(){
// return this.product.reduce((sum,x) =>
// ({count: 1,
// price:sum.price+x.count*x.price}),
// {quantity: 1, price: 0}).price;
//}
}
basket.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { UserInterface } from 'src/app/core/interfaces/user/user.interface';
import { ProductInterface } from '../../interfaces';
@Injectable({
providedIn: 'root'
})
export class BasketService {
url = 'http://localhost:3000';
basket = new BehaviorSubject([]);
basketCount = new BehaviorSubject(0);
product = [];
basketService: any;
userId: number;
constructor(private http: HttpClient) {
this.setToLocalStorage();
}
setToBasket(product): void {
this.setToLocalStorage(product);
console.log(product);
}
removeFromLocalstorage(id) {
var basket = JSON.parse(localStorage.getItem("basket"));
var index = basket.findIndex(x => x.id == id);
basket.splice(index, 1);
localStorage.setItem("basket", JSON.stringify(basket));
}
private setToLocalStorage(product?): void {
if (!localStorage.getItem("basket")) {
localStorage.setItem("basket", JSON.stringify([]));
} else {
this.basket.next(JSON.parse(localStorage.getItem("basket")));
this.basketCount.next(JSON.parse(localStorage.getItem("basket")).length);
}
if (!product) {
return
}
const basket = JSON.parse(localStorage.getItem("basket"));
basket.push(product);
localStorage.setItem("basket", JSON.stringify(basket));
this.basket.next(basket);
this.basketCount.next(basket.length);
}
getOrders(): Observable<Array<UserInterface>> {
return this.http.get<Array<UserInterface>>(`${this.url}/orders`);
}
// getOrderItem(): Observable<Array<ProductInterface>> {
// return this.http.get<Array<ProductInterface>>(`${this.url}/orders`);
// }
updateOrders(user: UserInterface) {
return this.http.put<Array<UserInterface>>(`${this.url}/orders`, user);
}
addOrder(user: UserInterface) {
return this.http.post<Array<UserInterface>>(`${this.url}/orders`, user);
}
}
basket.component.html
...
<app-user-order class="user-order"
(update)="updateOrders($event)"
(newUser)="addOrder($event)">
</app-user-order>
в json передается обьект:
"orders": [
{
"id": "1",
"firstName": "Иван",
"secondName": "Иванов",
"surname": "",
"city": "Львов",
"postNumber": "123",
"phone": "0999999999",
"addItionalInfo": ""
}
]
Ответы (1 шт):
Автор решения: Vladislav Rayta
→ Ссылка
добавил в basket.component строку - user.product = this.product;
addOrder(user: UserInterface): void {
user.product = this.product;
this.basketService.addOrder(user)
.subscribe(() => {
this.getOrder();
});
}
и добавил в user.interface
export class UserInterface {
.............
product: any;
}