2017-03-01 116 views
-1

我需要使用类型脚本将函数的返回值分配给局部变量。下面,我已清楚解释它:如何将函数的返回值赋给局部变量?

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

    } 

这里我处理答应

+0

您正在使用的承诺? –

+0

http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

+0

雅我在这个代码中使用 –

回答

1

你需要返回一个承诺比从代码的变量。就像这样:

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

添加后,我得到一个错误,如无法读取属性'然后'的未定义 –

+0

编辑我的答案。您稍后进行了编辑,因此需要编辑我的答案。 –

+0

感谢它会工作,你节省了我的时间 –

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;) 
+0

嘿,我还没有尝试在两个实例都使用'then()'。当我们返回一个承诺时,我们应该只在必须完成的时候使用'then()',不是吗?纠正我,如果我错了。 :) –

+0

您可以链接建议链接。从我以为OP想要在不同位置访问/保存数据的问题来看。 –

+0

好的。了解。 :) –

相关问题