如何将选定的(从homeComponent引导卡)传递到角度6中的另一个组件(favourtiesComponent)?

时间:2018-10-17 04:20:11

标签: arrays angular multidimensional-array

示例::单击书名(出售法拉利的和尚..)时,我想将“选定的一个”传递给“收藏夹”组件。默认情况下,它会添加所有项目在一个数组中。

HomeComponent:(如何在单击时添加单个项目,而不是将所有项目添加到favourtiesComponent中?)

enter image description here

收藏夹组件:

enter image description here

应用程序模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { FormInputComponent } from './form-input/form-input.component';
import { MyBookService } from './mybook.service';
import { HeaderComponent } from './header/header.component';
import { FavsComponent } from './favs/favs.component';
import { HomeComponent } from './home/home.component';
import { FavouriteService } from './favs.service';

const appRoutes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  {path: 'home', component: HomeComponent},
  {path: 'favourites', component: FavsComponent},
];

@NgModule({
  declarations: [
    AppComponent,
    FormInputComponent,
    HeaderComponent,
    FavsComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [MyBookService, FavouriteService],
  bootstrap: [AppComponent]
})
export class AppModule { }

HomeComponent.html

  <!-- loading form -->
  <app-form-input></app-form-input>

  <!-- output -->
  <div class="card text-white bg-dark" style="max-width: 18rem;"
  *ngFor="let book of myBooks">
      <div class="card-header" (click)="onAdd()"> {{ book.title }} </div>
      <div class="card-body">
        <!-- <h5 class="card-title">Dark card title</h5> -->
        <p class="card-text"> {{ book.content }} </p>
      </div>
  </div>

HomeComponent.ts

import { Component, OnInit, Input, EventEmitter } from '@angular/core';
import { MyBookService } from '../mybook.service';
import { Book } from '../book.model';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  myBooks: Book[];

  constructor(private bookService: MyBookService) {}

  ngOnInit() {
    this.myBooks = this.bookService.getBooks(); // Loading books

    // Listening to changes
    this.bookService.booksChanged
      .subscribe(
        (book: Book[]) => {
          this.myBooks = book;
        }
      );
  }

  onAdd() {
    this.bookService.addedBooks(this.myBooks);
  }
}

MyBookService.ts

import { Book } from './book.model';
import { Subject } from 'rxjs';
import { FavouriteService } from './favs.service';
import { Injectable } from '@angular/core';
import { Favourites } from './favs/fav.model';

@Injectable()
export class MyBookService {

  booksChanged = new Subject<Book[]>();
  bookSelected = new Subject<Book>();

  constructor(private favService: FavouriteService) {}

  private myBooks: Book[] = [
    new Book('A Monk who sold his ferrari', 'A burning sense of passion is the most potent fuel for your dreams.'),
    new Book('The Secret', 'You are already incredibly blessed, you just haven’t noticed.')
  ];

  getBooks() {
    return this.myBooks.slice();
  }

  addBooks(book: Book) {
    this.myBooks.push(book);
    this.booksChanged.next(this.myBooks.slice());
  }

  addedBooks(favBook: Favourites[]) {
    this.favService.addedFavBooks(favBook);
    console.log('favBook: ', favBook);
  }

}

FavouritiesService:

  private favBooks: Favourites[] = [
  ];

  getFavbooks() {
    return this.favBooks.slice();
  }

  addedFavBooks(favBooks: Favourites[]) {
    this.favBooks.push(...favBooks);
    this.favBooksChanged.next(this.favBooks.slice());
  }
}

FavouriteComponent.html

<div class="container mt-3"> 
  <h3 class="mb-3">My Favourties: </h3>
</div>

<!-- output -->
  <div class="card text-white bg-dark" style="max-width: 18rem;"
  *ngFor="let favBook of favBooks">
      <div class="card-header"> {{ favBook.title }} </div>
      <div class="card-body">
        <p class="card-text"> {{ favBook.content }} </p>
      </div>
  </div>

FavouritesComponent.ts

import { Component, OnInit } from '@angular/core';
import { FavouriteService } from '../favs.service';
import { Favourites } from './fav.model';

@Component({
  selector: 'app-favs',
  templateUrl: './favs.component.html',
  styleUrls: ['./favs.component.css']
})
export class FavsComponent implements OnInit {
  favBooks: Favourites[];
  favBook: Favourites;

  constructor(private favService: FavouriteService) {}

  ngOnInit() {
    // this.myBooks = this.bookService.addedBooks(); // Loading books
    this.favBooks = this.favService.getFavbooks();

    this.favService.favBooksChanged
      .subscribe(
        (favs: Favourites[]) => {
          this.favBooks = favs;
        }
      );
  }
}

1 个答案:

答案 0 :(得分:0)

每当选择一本书时,仅将该书添加到服务中。为此,可以通过HTML将当前选定的书传递给component.ts,如下所示。

修改后,代码可能如下所示。

HomeComponent.html

  <!-- loading form -->
  <app-form-input></app-form-input>

  <!-- output -->
  <div class="card text-white bg-dark" style="max-width: 18rem;"
  *ngFor="let book of myBooks">
      <div class="card-header" (click)="onAdd(book)"> {{ book.title }} </div>
      <div class="card-body">
        <!-- <h5 class="card-title">Dark card title</h5> -->
        <p class="card-text"> {{ book.content }} </p>
      </div>
  </div>

HomeComponent.ts

import { Component, OnInit, Input, EventEmitter } from '@angular/core';
import { MyBookService } from '../mybook.service';
import { Book } from '../book.model';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  myBooks: Book[];

  constructor(private bookService: MyBookService) {}

  ngOnInit() {
    this.myBooks = this.bookService.getBooks(); // Loading books

    // Listening to changes
    this.bookService.booksChanged
      .subscribe(
        (book: Book[]) => {
          this.myBooks = book;
        }
      );
  }

  onAdd(selectedBook) {
    this.bookService.addedBooks([selectedBook]);
  }
}