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

时间:2017-03-01 10:24:11

标签: angular typescript ionic2

我需要使用Type Script将函数的返回值赋给局部变量。下面我已经清楚地解释了它:

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;
}

并且这样称呼它:

let res = this.getdetail1(store);

看到这是我的登录服务代码

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

  }

这里我处理承诺

2 个答案:

答案 0 :(得分:2)

您需要从代码中返回承诺而不是变量。像这样:

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

并且这样称呼它:

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

答案 1 :(得分:0)

你需要做承诺链。请参阅解释here

尝试:

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

this.getdetail1(store).then(data=>this.res=data;)
相关问题