2016-05-17 6 views
0

に私はangularjs2とイオン2使用変数この他の機能

内の変数thisに問題がある、私はこれのfuctionを持っている:

getAnuncio(id_anuncio){ 
    console.log(id_anuncio) 
    var token=this.local.get('token')._result; 
    var headers= new Headers(); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    headers.append('Authorization', 'Token '+token); 
    datos="id_anuncio="+id_anuncio; 
    this.http.post('http://127.0.0.1:8000/envios/getAnuncioPorId/',datos , { 
     headers: headers 

    }) 

    .subscribe(success => { 
     this.anuncio=success.json(); 
     console.log("BIENNN"); 
     console.log(success); 
     console.log(this.anuncio); 
     return this.anuncio; 



    } 

} 

私は別の関数からそれを呼び出す:

cargarMapa(){ 

    this.anuncio=this.getAnuncio(this.envio.anuncio); 
    console.log(this.anuncio); 
    //console.log(anuncio); 
    //this.getOferta(this.envio.oferta); 
    //console.log(this.oferta) 
} 

しかし、this.anuncioを記録しようとすると、定義されていません。

他の機能から使用するには、変数にデータを格納する必要があります。

誰かが私を助けることができますか? https://github.com/p02diada/cyclaClientv2/blob/master/app/pages/sending-details/sending-details.js

答えて

0

あなたはこのためにdoオペレータをこのように活用することもできます:ここで

はコードである

getAnuncio(id_anuncio){ 
    console.log(id_anuncio) 
    var token=this.local.get('token')._result; 
    var headers= new Headers(); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    headers.append('Authorization', 'Token '+token); 
    datos="id_anuncio="+id_anuncio; 
    this.http.post('http://127.0.0.1:8000/envios/getAnuncioPorId/',datos , { 
    headers: headers 

    }) 
    .map(res => success.json()) 
    .do(data => { 
    this.anuncio = data; 
    }); 
} 

あなたはgetAnuncio方法の外に観測可能で購読することができますこの方法:

this.anuncio=this.getAnuncio(this.envio.anuncio).subscribe(
    (anuncio) => { 
    // do something 
    console.log(anuncio); 
    } 
); 

物事は非同期であることを忘れないでください。

あなたは、キャッシュの種類を実装し、次を使用する場合:

getAnuncio(id_anuncio){ 
    if (this.anuncio) { 
    return Observable.of(this.anuncio); 
    } else { 
    var token=this.local.get('token')._result; 
    var headers= new Headers(); 
    (...) 
    } 
} 

直接this.anuncioを使用することにより、データがあることを確認することができないということです...

+0

感謝あなたの答えはあなたがそれは動作しません。 オリジナルの例外:TypeError:this.http.post(...)。doは関数ではありません –

+0

ようこそ! 'do'演算子を含める必要があります。この質問を参照してください:http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276 'map'を' do'で置き換えてください... –

+0

私は今 'do'演算子を含んでいます。それは私にエラーを与えませんが、 'getAnuncio'関数の外で' this.anuncio'をまだ使用することはできません。非同期のために 'setTimeout'で試してみましたが、動作しません。 –

関連する問題