2016-05-02 4 views
0

forループ内で更新された変数の値を取得し、スコープ外にアクセスします。このためAngular2/Javascript - forループ内で生成された変数の新しい値を取得します。

私が持っている: Page.html

<div [options]="Pages"> 
    <div *ngFor="#cat of category"> 
     <div class="newCategory">The new category will appear here!</div> 
    <div> 
</div> 

Page.js

constructor(viewCtrl, http, navParams) { 
    this.viewCtrl = viewCtrl; 
    this.navParams = navParams; 
    this.http  = http; 
    this.category = null; 

    this.http.get('https://website.com/api', { search }).subscribe(data => { 
    this.category = data.json().results; 
    }); 

    //I want to print the new value of 'this.category' here 
    //e.g: console.log(this.category); 

    this.Pages = { 
    pagination: '.swiper-pagination', 
    slidesPerView: 1, 
    paginationClickable: true, 
    paginationBulletRender: function (index, className) { 
    //also I want to access it here 
    return '<span class="' + className + '">' + this.category[index+1] + '</span>'; 
    } 
    } 
} 

私は、新しい値を読み取るためにグローバル変数を持っている必要がありますか変数?それとも別のものが必要ですか?

+0

新しいカテゴリの 'category'値はどこから来るべきですか? –

+0

それはREST APIから来るでしょう –

答えて

1

を変更する必要がある

<div class="newCategory">{{cat}}</div> 

、その後、あなたが格納されますすることができます値の範囲外this.http.get()

+0

あなたはそれを釘付けにしました!どうもありがとうございます!!! –

1

質問についてはわかりません。推測:コンストラクタはそれを行うための最善の方法は、アレイ内でthis.categoryやループ、それを格納することです

constructor(viewCtrl, http, navParams) { 
     this.viewCtrl = viewCtrl; 
     this.navParams = navParams; 
     this.http = http; 
     this.category = null; 

     this.http.get('https://website.com/api', { search }).subscribe(data => { 
     this.category = data.json().results; 
     //I want to print the new value of 'this.category' here 
     //e.g: console.log(this.category); 


       this.Pages = { 
      pagination: '.swiper-pagination', 
      slidesPerView: 1, 
      paginationClickable: true, 
      paginationBulletRender: function (index, className) { 


      //also I want to access it here 


      return '<span class="' + className + '">' + this.category[index+1] + '</span>'; 
      } 
      } 


     }); 
     } 
+0

答えをありがとう、しかし私はそれが必要ではないので、私はそれがJS /角度コードでそれを得ることです。 –

+0

あなたが作成した編集については、変更する必要のあるサービスは何ですか?詳細を教えてください –

+0

'http.get()'が非同期で実行され、 'subscribe(...)'の後のコードがデータが到着する前に実行されます。ときどき後でデータがサーバから到着すると、 'subscribe(...)'に渡されたコードが呼び出されます。受け取ったデータを 'subscribe(...)'コールバックの中で処理するコードを実行する必要があります。 –

関連する問題