[英]How to assign a return value of function to local variable?
我需要使用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);
});
});
}
我在这里履行诺言
您需要返回一个承诺,而不是代码中的变量。 像这样:
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);
});
您将需要做诺言链接。 请参阅此处的说明。
尝试:
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;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.