简体   繁体   中英

Angular 2 - Getting object id from array and displaying data

I currently have a service that gets an array of json objects from a json file which displays a list of leads. Each lead has an id and when a lead within this list is clicked it takes the user to a view that has this id in the url ie ( /lead/156af71250a941ccbdd65f73e5af2e67 )

I've been trying to get this object by id through my leads service but just cant get it working. Where am I going wrong?

Also, i'm using two way binding in my html.

SERVICE

  leads;

  constructor(private http: HttpClient) { }

  getAllLeads() {
    return this.http.get('../../assets/leads.json').map((response) => response);
  }

  getLead(id: any) {
    const leads = this.getAllLeads();
    const lead = this.leads.find(order => order.id === id);
    return lead;
  }

COMPONENT

  lead = {};

  constructor(
    private leadService: LeadService,
    private route: ActivatedRoute) {

      const id = this.route.snapshot.paramMap.get('id');
      if (id) { this.leadService.getLead(id).take(1).subscribe(lead => this.lead = lead); }

   }

JSON

[
  {
    "LeadId": "156af71250a941ccbdd65f73e5af2e66",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "Fred Dibnah",
    "LeadNumber": "1603041053",
  },
  {
    "LeadId": "156af71250a999ccbdd65f73e5af2e67",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "Harry Dibnah",
    "LeadNumber": "1603021053",
  },
  {
    "LeadId": "156af71250a999ccbdd65f73e5af2e68",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "John Doe",
    "LeadNumber": "1603021053",
  }
]

You didn't used the newly created leads array ( const leads is not this.leads ), so do this:

getLead(id: any) {
    return this.getAllLeads().find(order => order.LeadId === id);
}

And change your map to flatMap , because from the server you get an array, but you have to transform it to a stream of its items:

getAllLeads() {
    return this.http.get('../../assets/leads.json').flatMap(data => data);
}

Don't forget to import it if you have to: import 'rxjs/add/operator/flatMap';

You can have getLead in your component level itself since you are not making any api to get the information. In your component,

this.lead = this.leads.find(order => order.id === id);

or to make the above service work, just do leads instead of this.leads

 const lead = leads.find(order => order.id === id);

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