简体   繁体   中英

How to assign a return value of function to local variable?

I need to assign a return value of function to a local variable using Type Script. Below I have explained it clearly:

getdetail1(store){              
    let Cust_id=this.sharedata.latus_lead.m_type
    let url="http:domain.com"
    console.log(url);
    let res;
    this.loginservice.leaddata = null;
    this.loginservice.getdetails(url).then(data=>{
        let lead=data;
        this.details=lead[0];
        res=lead[0];                          
    });
    return res;
}

And calling it like this:

let res = this.getdetail1(store);

see this is my login service code

getdetails(query){
       if (this.leaddata) {
        // already loaded data  
        console.log("already data loaded lead") ;
        return Promise.resolve(this.leaddata);
      }
    // don't have the data yet
    return new Promise(resolve => {
      // We're using Angular HTTP provider to request the data,
      // then on the response, it'll map the JSON data to a parsed JS object.
      // Next, we process the data and resolve the promise with the new data.
        this.http.get(query)
        .map(res => res.json())
        .subscribe(data => {
          // we've got back the raw data, now generate the core schedule data
          // and save the data for later reference
          this.leaddata = data;
          resolve(this.leaddata);
        });
    });

  }

here i handle promise

You need to return a promise than a variable from the code. Like this:

getdetail1(store){              
    let Cust_id=this.sharedata.latus_lead.m_type
    let url="http:domain.com"
    console.log(url);
    let res;
    this.loginservice.leaddata = null;

    return this.loginservice.getdetails(url);
}

And calling it like this:

this.getdetail1(store)
    .then((data) => {
        let res = data;
        console.log("Your data: ",res);
    })
    .catch((err) => {
        console.log("Error occurred :", err);
    });

You will need to do promise chaining. See explanation here .

Try:

getdetail1(store){              
             let Cust_id=this.sharedata.latus_lead.m_type
             let url="http:domain.com"
              console.log(url);
              this.loginservice.leaddata=null;
                 return this.loginservice.getdetails(url).then(data=>{
                    let lead=data;
                     this.details=lead[0];
                    return lead[0];                          
             });//return the promise call as well as the data within

And:

this.getdetail1(store).then(data=>this.res=data;)

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