如何让* ngFor仅显示不同组件中单击元素的特定数据? Angular4

时间:2017-05-09 08:35:34

标签: angular components ngfor

我正在尝试通过做一些项目来学习Angular。其中一个是Reader

我有3个组件:Bookshelf,Book和Chapter。 当我从json文件中检索数据时,在BookComponent中,* ngFor显示所有书籍,但我只需显示所选/点击书籍的数据。 我的代码如下所示:

bookshelf.component.html

<div class="bookshelf row" >
  <div class="book col-md-3" *ngFor="let book of books; let i=index">
    <a [routerLink]="['/book/:id']">
      <img src="{{ book.cover }}"/>
      <h3 class="title">{{ book.title }}</h3>
      <p class="author">{{ book.author }}</p>
    </a>
  </div>
</div>

bookshelf.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { DataService } from '../data.service'; 
import { Http } from '@angular/http'; 

@Component({   
  selector: 'app-bookshelf',   
  templateUrl: './bookshelf.component.html',   
  styleUrls: ['./bookshelf.component.css'] 
}) 

export class BookshelfComponent implements OnInit {   
  books = [];   

  constructor(private dataService: DataService) {   } 

  ngOnInit() {
    this.dataService.fetchData().subscribe(
      (data) => this.books = data
    )
  }
}

book.component.html

<a class="button back" [routerLink]="['']">Back</a>
<div class="book-detail" *ngFor="let book of books; let i=index">
  <img src="{{ book.cover }}" />
  <h3 class="title">{{ book.title }}</h3>
  <p class="author">{{ book.author }}</p>
  <p class="description">{{ book.description }}</p>
  <a class="button" [routerLink]="['/chapter']">Read</a>
</div>

book.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Http } from '@angular/http';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
  books = [];

constructor(private dataService: DataService) {}
ngOnInit() {
  this.dataService.fetchData().subscribe(
    (data) => this.books = data
    )
  }
}

books.json

[
  {
    "title": "Metamorphosis",
    "cover": "../assets/metamorphosis.jpg",
    "author": "Franz Kafka",
    "description": "The story...",
    "chapters": [
      {
        "title": "I",
        "paragraphs": ["One morning... "]
      },
      {
        "title": "II",
        "paragraphs": ["No one... "]
      },
{
    "title": "Strange Case of Dr Jekyll and Mr Hyde",
    "cover": "../assets/drjekyllmrhyde.jpg",
    "author": "Robert Louis Stevenson",
    "description": "London lawyer...",
    "chapters": [
      {
        "title": "Story of the Door",
        "paragraphs": ["Mr. Utterson... "]
      },
      {
        "title": "Search for Mr. Hyde",
        "paragraphs": ["That evening ... "]
      },
{
    "title": "Heart of Darkness",
    "cover": "../assets/heartofdarkness.jpg",
    "author": "Joseph Conrad",
    "description": "The story...",
    "chapters": [
      {
        "title": "I",
        "paragraphs": ["The Nellie... "]
      },
      {
        "title": "II",
        "paragraphs": ["\"One evening... "]
      }
    ]
  }
]

我能够用旧的AngularJs中的“$ routeParams”来做这个,现在我觉得它已被弃用了。 有谁知道我怎么才能只显示特定的书籍数据?

1 个答案:

答案 0 :(得分:1)

Maxime为您提供了一个很好的链接,我只是想我会使用JSON文件呈现该版本。

您的代码看起来很不错。你似乎唯一想念的就是路由部分和获得那本书。

因此,您的JSON目前每本书都没有id,但我在代码中添加了一个。 因此,当您显示图书时,您的路由器链接应如下所示:

<a [routerLink]="['/book/'+book.id]">

我们将book id添加为参数。导航时,我们获取路径参数并进行http调用以获取该特定书籍,因此将ActivatedRoute注入您的book-component构造函数,然后OnInit应如下所示:

 ngOnInit() {
    this.route.params.subscribe(params => {
        let id = params['id']; // get parameter
        this.dataService.getBook(id) 
          .subscribe(data => {
            this.book = data;
          })
    )}
  }

然后相应的服务功能getBook如下所示,我们获取所有图书,然后根据ID找到正确的图书:

getBook(id) {
  return this.http.get('url')
    .map(res => res.json().find(x => x.id == id))
}

那应该是:)同时检查这个

Plunker