我试图使用Angular 8构建一个示例Restaurants应用程序。我正在使用@Input()将单个餐厅数据作为对象从父组件传递到RestaurantCardComponent进行显示。 RestaurantCardComponent中的每张卡片都有一个“添加到收藏夹”按钮,该按钮应将特定餐厅推入User模型类中的收藏夹数组。但是,当我尝试推入对象时,第一个对象被推入没有问题,但是随后单击“添加到收藏夹”仅替换了先前推入的对象。下面是CardViewComponent的HTML代码。
<app-restaurant-card [restaurant]="collection" *ngFor="let collection of collections"></app-restaurant-card>
这是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)
);
}
}
如何在不替换以前推送的数组的情况下将饭店添加到收藏夹数组?
答案 0 :(得分:1)
创建一个可能名为UserService的新服务,或者将“ user”属性添加到AuthService而不是组件中,如果将用户添加到组件中,则每个组件都有一个实例。