Reputation: 143
I am having an issue switching from a promise to an http observable in Angular2. I have 2 methods getEmployees() and getEmployee(id:number).
I was able to successfully switch the getEmployees() however I am getting various error messages(filter doesn't exist on type observable) when trying to switch the getEmployee(id:number)
Original - Service.ts
getEmployee(id: number) {
return Promise.resolve(EMPLOYEES).then(
employees => employees.filter(employee => employee.id === id)[0]
);
1st try service.ts
getEmployee(id: number) {
return this.http.get(employeesUrl + id).map(employee => employee.id === id)[0]
);
Original - Component.ts
let id = +curr.getParam('id');
this.employeeService.getEmployee(id).then(employee => {
this.employee = employee;
});
Upvotes: 0
Views: 1038
Reputation: 1037
You need to return an observable to subscribe to:
This returns an observable that is going to be mapped to employees with id equals to the id passed.
getEmployee(id: number) {
return this.http.get(employeesUrl + id).map(res => res.json()).map(employee => employee.id === id);
);
Then, you can subscribe to it like this, and the first call back of the subscription is the next
or successful
callback:
let id = +curr.getParam('id');
this.employeeService.getEmployee(id).subscribe(employees => {
maybe this.employee = employees[0];
});
Second callback is error
, third callback is complete
.
FYI, didnt test it but its basically the idea behind observables.
Edit: @Sasxa made me realize i was missing a really big step haha.
Upvotes: 0
Reputation: 41264
http.get()
returns a observable of Response object. You need to get the data from it, usually by calling it's json()
method. Then you can apply transformations to your data - map, filter etc.
getEmployee(id: number) {
return this.http.get(employeesUrl + id)
.map(response => response.json())
.map(employee => employee.id === id)[0]
);
Observable this service returns is cold - it won't do anything until you explicitly ask by subscribing to it in your component:
let id = +curr.getParam('id');
this.employeeService.getEmployee(id).subscribe(employee => {
this.employee = employee;
});
Upvotes: 2