Angular – How to call an http method without the observable in Angular 2

angular

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

Best Answer

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););
Related Topic