似乎是基本的异步实现,但我无法从Angular5服务获取值。以下是服务方法:
async getEmployees() {
return await this.http.get<Employee[]>('...')
.pipe(
map(employees => {
const directory = [];
employees.forEach(employee => {
directory.push({
firstName: employee.firstName,
lastName: employee.lastName,
phone: employee.phone,
email: employee.email,
city: employee.address.city,
avatar: employee.avatar
});
});
return directory;
}),
toArray()
)
.toPromise();
}
以下是我在组件中调用上述服务方法的方法:
export class StarmarkDirectoryComponent implements OnInit {
public employees: any = [];
private employeeService: StarmarkEmployeeService;
constructor(employeeService: StarmarkEmployeeService) {
this.employeeService = employeeService;
}
async ngOnInit() {
this.employees = await this.employeeService.getEmployees();
}
}
这是模板:
<div class="row">
<div class="col-md-4">
<select id="city" class="form-control">
<option value="">FILTER BY CITY NAME</option>
<option *ngFor="let employee of employees; let a = index">
{{ employee.city }}</option>
</select>
</div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
<pre>
{{ employees | json }}
</pre>
员工在<pre>
标记内呈现为JSON。但是,我需要迭代我的模板,但不了解我需要如何获得我的价值。我我能够使用{{ employees | json }}
获取我的返回值但是我无法使用*ngFor
进行迭代
答案 0 :(得分:0)
您应该订阅getEmployee方法。 实施例
this.employeeService.getEmployee()
.subscribe((data)=>{
this.employees = data;
});
&#34;请原谅任何拼写错误&#34;
答案 1 :(得分:0)
有趣的是,当我从toArray()
移除pipe()
时,它正常工作。