简体   繁体   中英

Convert http request / add a function in case of success. ::Typescript & Angular2

I have a http request:

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
    }));
};

And in case of success , I want to make one line code:

this.vars.map((v,i) => v.push(this._values[i].value));

My question is in normal ajax it would be like .success: function(){}

How to convert my code into something like this?

Thank you in advance.

EDIT

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
      })).then(console.log());
};

Angular2 is unable to resolve the then variable. What have I to import into component to make it work?

The http function uses observables. You can do something like this:

 private getValues() {
      this._watchlistElements.map(v =>
        this.http.get('http://localhost/getValue/' + v.xid).map(res=>res.json())
          .subscribe(res => {
           //success
          },
         error=>{
             //error logic
          });
      }

If you want to use only promises,

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .toPromise()
      .then(res=>{res.json()}).catch(errorFunction);
};

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