2016-09-13 3 views
0

内部グローバル変数へのhttp購読()メソッドからの戻り値を代入することができません:2角度 - 私は、角2</p> <p>recent.service.tsでhttp.getを使用してJSONファイルを取得していますコンポーネント

import { Http, Response } from '@angular/http'; 
//import { Observable } from '../../../../../../node_modules/rxjs/Observable'; 
import { Observable } from '../../../../../../node_modules/rxjs/Rx'; 
import { Injectable } from '@angular/core'; 



@Injectable() 
export class RecentService { 

    private _url = 'http://localhost:3001/api/uploadedFiles'; 

    constructor(private _http: Http) { 


    } 

    getJson() { 

     return this._http.get(this._url) 
      .map(res => res.json()); 

    } 

} 

recent.component.ts:

import {Component, OnInit} from '@angular/core'; 
    import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle} from    '@angular/common'; 
    import {RecentService} from './recent.service'; 
    import {HTTP_PROVIDERS} from '@angular/http'; 
    import {Observable} from 'rxjs/Observable'; 


    @Component({ 
    selector: 'recent', 
    pipes: [], 
    providers: [RecentService, HTTP_PROVIDERS], 
    styleUrls: ['/app/pages/content/components/recent.styles.css'], //might need to change reference 
    template: require('./recent.html') // `<strong>My edit page</strong>` 
    }) 
    export class Recent implements OnInit{ 

     allFiles; 
     public allFiles_error:Boolean = false; 
     openModalWindow:boolean=false; 
     images = []; 
     currentImageIndex:number; 
     opened:boolean=false; 
     imgSrc:string; 

    constructor(private _recentService: RecentService) { 
     this._recentService.getJson() 
      .subscribe(data => { 
      this.allFiles = data; 
      console.log("allFiles: ", this.allFiles); 
      console.log(this.allFiles.length); 
      for(var i = 0; i < this.allFiles.length; i++) { 
       this.images.push({ 
       thumb: this.allFiles[i].url, 
       img: this.allFiles[i].url, 
       description: "Image " + (i+1) 
       }); 
      } 
      console.log("Images: ", this.images); 
      }, 
      err => { this.allFiles_error = true }, 
      () => console.log('Completed!') 
    ); 

    } 

    ngOnInit() { 

    console.log(this.images.length); 
    console.log(this.images); 
    console.log(typeof this.images); 
    } 
    //this is the function where I want to access this.images 
    openGallery(index) { 
     if(!index) { 
     this.currentImageIndex = 1; 
     } 
     this.currentImageIndex = index; 
     this.opened = true; 
     for (var i = 0; i < this.images.length; i++) { 
     if (i === this.currentImageIndex) { 
     this.imgSrc = this.images[i].img; 
     break; 
     } 
    } 
    console.log(this.imgSrc); 
    } 

this.allFiles JSONオブジェクトの配列です。私はthis.allFilesから選択したデータをthis.imagesに保存しようとしています。私はまた、コンポーネント全体を通してグローバル変数としてthis.imagesにアクセスしたいと思いますが、http.get()で非同期呼び出しが行われているため、これを行うことができませんでした。私は自分のhtml内で非同期パイプを試しましたが、それもエラーにつながりました。 this.imagesにグローバルにアクセスする方法はありますか?

ありがとうございます。

+0

「グローバル」を作成するには、静的メンバーと記憶域を持つ共有コンポーネント/モジュールを作成し、他のすべてのコンポーネントからのものを使用できます。 – rook

答えて

2

私はTypeScriptとAngular2の経験はほとんどありませんが、矢印機能とthisというキーワードに問題があると思います。エラー関数で角括弧を使用すると、その内部にあるthisは、必要な上位クラスではなく関数自体の参照を開始します。あなたのエラー処理にも同じことをしてください。

また、コンストラクタからコールを削除し、そのためにngOnInitを使用してください。

このような何かを試してみて、私に知らせてください:

あなたが this.allFilesにアクセスしたいん
export class Recent implements OnInit{ 
    allFiles; 
    public allFiles_error:Boolean = false; 
    openModalWindow:boolean=false; 
    images = []; 
    currentImageIndex:number; 
    opened:boolean=false; 
    imgSrc:string; 

    constructor(private _recentService: RecentService) { } 

    ngOnInit() { 
     this._recentService.getJson().subscribe(
      data => initData(data), 
      err => handleError(), 
      () => console.log('Completed!')); 
    } 

    initData(data){ 
     this.allFiles = data; 
     console.log("allFiles: ", this.allFiles); 
     console.log(this.allFiles.length); 
     for(var i = 0; i < this.allFiles.length; i++) { 
      this.images.push({ 
      thumb: this.allFiles[i].url, 
      img: this.allFiles[i].url, 
      description: "Image " + (i+1) 
      }); 
     } 
     console.log("Images: ", this.images); 
     console.log(this.images.length); 
     console.log(this.images); 
     console.log(typeof this.images); 
    } 

    handleError() { 
     this.allFiles_error = true; 
    } 
} 
+0

はあなたのコードを試しましたが、私はまだthis.imagesが空の配列を返す問題を抱えています。私は主な問題は、this.imagesが生成される前に返されるということです。 – rads89

+0

'this.images'をどこに返すのか分かりません – Fedaykin

+0

現在、' .subscribe() 'メソッドの後に' ngOnInit() 'の中に' this.images.length'を記録しようとしています。コンソールで。最終的に、私は自分のhtmlの中の 'this.images'にアクセスし、 'this.images'配列を直接使用するコンポーネント内のメソッドにアクセスする必要があります。 – rads89

0

をパイプなしで追加することができます。 Observablesからの購読のため、Angular2はテンプレートを再レンダリングして更新されるため、更新されます。

コンポーネントから他の機能にアクセスする必要がある場合は、。サブスクライブ関数内に関数呼び出しを追加します。

+0

this.allFilesから選択された値を 'this.images'に代入するときに' subscribe() 'メソッドの' this.allFiles'にアクセスするだけです。 'this.images'は' .subscribe() 'の中で期待通りに値をコンソールに記録します。この問題は、別の関数の中で 'this.images'を繰り返し処理しようとしているときに発生します。さらに、私はそれらの関数をテンプレートから呼び出そうとしています。 – rads89

+0

元の投稿を編集して、 'this.images'の値を使用している関数の1つを表示しました。コンソール上では、 'this.imgSrc'は未定義と表示されています。これはおそらく問題が原因です。 – rads89

+0

this.imagesはまだ準備ができていないため、テンプレートから直接これらの関数を呼び出すことはできません。サブスクライブコールバックが呼び出されると準備が整います。したがって、関数はサブスクライブから呼び出す必要があります。テンプレートに必要な場合は、this.imagesが利用可能なときにトリガーをサブスクライブするときだけレンダリングする* ngIf状態を追加する必要があります。 – tibbus

関連する問題