2016-07-04 7 views
0

遠隔データを待つ伝統的な方法は、約束から離れていることを理解していますが、問題は作成した値を返す関数を作成する必要があります。 .then遠隔データを返す角度関数を作成し、約束を待つことを約束する

//inside controller 
$scope.someFunction = function(id){ 
    var returnVal; 
    $http.post(someURL,{_id:id}).then(
     function(r){ 
      //lets assume r.data = {id:123,name:'john doe'} 
      returnVal = r.data.name; 
     },function(r){ 
      console.error(r.statusText); 
      returnVal = 'error getting name' 
     }  
    ); 
    return returnVal; 
}; 

.thenがまだ呼び出されていなくても、リターンブロックを実行するため、問題はヌル結果を返すことです。

//the html is like this 
<main component> 
    <!--this main component will generate dynamic number of subs--> 
    <!--lets assume Seller is the main and sub is all the products he sold --> 
    <sub component sub-detail="the function that returns correct value"> 
     <!--I need to make $http request to get the product details for each product generated--> 
    </sub component> 
</main component> 
<another main component> 
    <!--generates another series of subs--> 
</another main component> 

です。私は、httpリクエスト

+0

あなたが外側の関数をしたい場合_async_に実行機能( 'http.post')を呼び出すのポイントは何同期するには? –

+0

私は別のサブコンポーネントを生成するtelerikコンポーネントを使用しています。サブコンポーネントを生成する前に属性を指定することができますが、リモートサービスからデータを取得する必要があります。 – anaval

+1

これがコントローラ内にある場合、なぜコールバック内にスコープモデルプロパティを割り当てるだけでなく、何かを返す必要がありますか? – charlietfl

答えて

-2

Updateからデータを返す関数を()が必要ですあなたのコード:

$scope.someFunction = function(id){ 
    var returnVal; 
    return $http.post(someURL,{_id:id}).then(
     function(r){ 
      //lets assume r.data = {id:123,name:'john doe'} 
      returnVal = r.data.name; 
      return returnVal; 
     },function(r){ 
      console.error(r.statusText); 
      returnVal = 'error getting name'; 
      return returnVal; 
     }  
    ); 
}; 
+0

それでも '.then 'でなければならない約束を返します。 –

+0

それを試してコメントしてください。あなたはそれを正しく試していないのですか?私は自分の地元で働いています。 plunkrに1分間表示されます。ちょうどダミーのポストソースを探して – mtamma

+0

確かに、それは動作します。 OPの要件を満たしていないだけです。 –

関連する問題