3

When I call this function the console.log() works, but the http.delete method never runs, I assume because I haven't subscribed to the observable.

Because I'm calling this from a button on a form, I don't care about returning anything so is there a way to just make the call?

  deleteCompany(id) { 
      console.log('from data service: ', id);
      this.http.delete(this.url + 'Companies/' + id + '?' + this.token).map(res => res.json());
   }

Edit: I went with this instead. Is this the correct way to handle this?

import 'rxjs/add/operator/toPromise';
...
return this.http.delete(this.url + 'Companies/' + id + '?' + this.token).toPromise();
1
  • "Edit:" looks fine. You can also call subscribe() without passing a callback. I think this makes it more obvious what the intent is. Aug 5, 2016 at 5:02

2 Answers 2

7

As @Gunter pointed out, you need to call subscribe if you want to use observable. You can convert observable to promise if you want something to be returned(as promises are not lazy) as following :

import 'rxjs/add/operator/toPromise';
     deleteCompany(id) { 
          console.log('from data service: ', id);
         return this.http.delete(this.url + 'Companies/' + id + '?' + this.token).toPromise();
       }

In order to consume it use then instead of subscribe in your component. e.g :

this._yourServiceName.deleteCompany(this._id).then((data)=> console.log(data), (err) => console.log("error occured", err););
2
  • Thanks for the answer. To ensure I understand (I'm very new at this), in your example you're mapping the response so that I have something to consume in my component and then using .promise to actually trigger the http call correct? So how does 'return' fit into this since I noticed you didn't use it?
    – Lee
    Aug 6, 2016 at 22:36
  • You are right. I forgot to return the observable(edited now). Generally, we use map (or any other method) to transform the data stream. Using map(res => res.json() will parse the response as JSON which we need not use here. toPromise method is going return a promise which gets resolved using then method in component.
    – candidJ
    Aug 7, 2016 at 19:20
2

No. Observables are lazy and won't do anything before subscribe or toPromise is called.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.