简体   繁体   中英

Selecting object from JSON array in Angular 4

working on an angular4 app that has 2 components/pages. the first component is related to the object id:1 and it is one page and the second component is related to id:2 and it is another page. both of these pages share the same template 'page.component.html'

how do get the first component to only render the object with id:1? and the same for the second component. I understand that right now as it is set up, each component is going to both objects in the array.

is there a way i can do this in the service or each component?

data.json

[
  {
    "id": 1,
    "array":
    [
      {
        "name": "name1.a",
        "title": "title1.a",
      },
      {
        "name": "name1.b",
        "title": "title1.b",
      },
      {
        "name": "name1.c",
        "title": "title1.c",
      }
    ],
  }
  {
    "id": 2,
    "array":
    [
      {
        "name": "name2",
        "title": "title2",
      }
    ]
  }
]

page.component.html

<div *ngFor="let set of sets">
  <p>{{set.name}}</p>
  <p>{{set.title}}</p>
</div>

page.component.ts

// Imports
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { page }  from '../page';
import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class GenreService {
  // Resolve HTTP using the constructor
  constructor (private http: Http) {} 
  private pagesUrl = '../assets/json/data.json';

   // Fetch all existing comments
   getPages() : Observable<Page[]>{
       // ...using get request
       return this.http.get(this.pagesUrl)
                      // ...and calling .json() on the response to return data
                       .map((res:Response) => res.json())
                       //...errors if any
                       .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
   }
}

page.ts

export class Page {
  constructor(
    public id: number,
    public array: array,
    public name: string,
    public title: string
  ){}  
}

page.component.ts

import { Component, OnInit } from '@angular/core';

import { Page } from './page';
import { PageService } from '../../services/page.service';

@Component({
  selector: 'page1',
  templateUrl: './page.component.html',
  providers: [ PageService ],
})
export class Page1Component implements OnInit {

  pages: Page[];
  errorMessage: string;


  ngOnInit() {
    this.getPages();
  }
  getPages() {
    this.genreService.getPages()
                    .subscribe(
                       pages => this.pages = pages,
                       error => this.errorMessage = <any>error);
  }
}

This will work good with you

<div *ngFor="let set of sets.array">
  <p>{{set.name}}</p>
  <p>{{set.title}}</p>
</div>

Maybe you can change the method getPages() for getPage(id: number) and filter by id. It would be like so:

getPage(id: number) : Observable<Page>{
   // ...using get request
   return this.http.get(this.pagesUrl)
                  // ...and calling .json() on the response to return data
                   .map((res:Response) => res.json())
                   // ... do antoher map an return the correct object
                   .map((data: Array<any>) => {
                     return data.find(x => x.id === id)
                   })
                   //...errors if any
                   .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}

With that fucntion it will only return the Page that you want, Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM