簡體   English   中英

Angular 2-從數組獲取對象ID並顯示數據

[英]Angular 2 - Getting object id from array and displaying data

我目前有一項服務,可從顯示線索列表的json文件中獲取json對象數組。 每個銷售線索都有一個ID,當單擊此列表中的銷售線索時,會將用戶帶到在URL中具有此ID的視圖,即(/ lead / 156af71250a941ccbdd65f73e5af2e67)

我一直在嘗試通過潛在顧客服務通過id獲取此對象,但無法使其正常工作。 我要去哪里錯了?

另外,我在HTML中使用兩種方式綁定。

服務

  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;
  }

零件

  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",
  }
]

你沒有使用新創建的leads陣列( const leadsthis.leads ),所以這樣做:

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

並將map更改為flatMap ,因為從服務器獲得了一個數組,但必須將其轉換為其項的流:

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

如果需要,不要忘記導入它: import 'rxjs/add/operator/flatMap';

您可以在組件級別本身中使用getLead,因為您沒有制作任何API來獲取信息。 在您的組件中

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

或使上述服務有效,只做leads而不是this.leads

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM