简体   繁体   English

如何将函数的返回值分配给局部变量?

[英]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. 我需要使用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;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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