简体   繁体   中英

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

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

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. eg :

this._yourServiceName.deleteCompany(this._id).then((data)=> console.log(data), (err) => console.log("error occured", err););

没有。在subscribetoPromise之前,Observables是懒惰的并且不会做任何事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM