2017-03-01 14 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

これを追加した後、私は不定の 'then'プロパティを読み取ることができません。 –

+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()'を使ってみました。私たちは約束を返すので、thenable()は、実行可能なアクションを実行する必要がある場合にのみ使用する必要があります。私が間違っているなら、私を訂正してください。 :) –

+0

リンクが示唆しているようにチェーンすることができます。質問から、私はOPが別の場所のデータにアクセスして保存したいと思った。 –

+0

Ok。理解しています。 :) –

関連する問題