Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - 阵列推送将覆盖先前推送的数据(Array push is overwriting previously pushed data)

I am trying to build a sample Restaurants app using Angular 8. I am using @Input() to pass individual restaurant data as object from the parent component to RestaurantCardComponent for displaying.(我正在尝试使用Angular 8构建一个示例Restaurants应用程序。我正在使用@Input()将单个餐厅数据作为对象从父组件传递到RestaurantCardComponent进行显示。)

Each individual card in RestaurantCardComponent has an 'Add to favorites' button which which should push that particular restaurants into a favorites array in the User model class.(RestaurantCardComponent中的每张卡片都有一个“添加到收藏夹”按钮,该按钮应将特定餐厅推入User模型类中的收藏夹数组。) However when I try pushing the object, the first object is pushed without any issue but thereafter clicking on 'Add to favorites' just replaces the previously pushed object.(但是,当我尝试推入对象时,第一个对象被推入没有问题,但是随后单击“添加到收藏夹”仅替换了先前推入的对象。) Below is the HTML code for the CardViewComponent.(以下是CardViewComponent的HTML代码。) <app-restaurant-card [restaurant]="collection" *ngFor="let collection of collections"></app-restaurant-card> Here is the RestaurantCardComponent typescript code:(这是RestaurantCardComponent的打字稿代码:) import { Component, OnInit, Input } from '@angular/core'; import { faHeart } from '@fortawesome/free-solid-svg-icons'; import { AuthServiceService } from '../services/auth-service.service'; import { User } from '../user'; import { RouterService } from '../services/router.service'; import { Restaurant } from '../restaurant'; @Component({ selector: 'app-restaurant-card', templateUrl: './restaurant-card.component.html', styleUrls: ['./restaurant-card.component.css'] }) export class RestaurantCardComponent implements OnInit { @Input() restaurant: Restaurant; faHeart = faHeart; user: User = new User(); constructor(private authService: AuthServiceService, private routerService: RouterService) { } ngOnInit() { // console.log(this.restaurant); this.authService.getUserData(parseInt(this.authService.getBearerToken())).subscribe( data => this.user = data, error => console.log(error.message)); } addToFavourites() { this.user.favourites.push(this.restaurant); this.authService.updateUserData(this.user).subscribe( updatedData => console.log(updatedData), error => console.log(error.message) ); } } How can I add the restaurants to the favorites array without replacing the previously pushed array?(如何在不替换先前推送的数组的情况下将饭店添加到收藏夹数组?)   ask by B Basak translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

创建一个可能称为UserService的新服务,或者将“ user”属性添加到AuthService而不是组件中,如果将用户添加到组件中,则每个组件都有一个实例。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...