0

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

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

oh damn, i forgot about the .json part haha, you are right.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.