我目前有一个服务从json文件中获取一个json对象数组,该文件显示了一个潜在客户列表。每个线索都有一个ID,当点击此列表中的线索时,它会将用户带到URL中具有此ID的视图,即(/ lead / 156af71250a941ccbdd65f73e5af2e67)
我一直试图通过我的潜在客户服务获取此对象,但是无法让它正常工作。我哪里错了?
另外,我在我的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",
}
]
答案 0 :(得分:1)
您没有使用新创建的leads
数组(const leads
不是this.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';
答案 1 :(得分:1)
您可以在组件级别拥有getLead,因为您没有使用任何api来获取信息。在您的组件中,
this.lead = this.leads.find(order => order.id === id);
或要使上述服务有效,只需执行 leads
而不是 this.leads
const lead = leads.find(order => order.id === id);