2016-09-13 1 views
0

나는 각 2각도 2 - HTTP로부터의 반환 값을 할당 구성 요소

recent.service.ts에 사용하여 JSON 파일 http.get을 얻고 내부 전역 변수() 메소드를 구독 할 수 없습니다 :

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'의 값을 사용하는 함수 중 하나를 보여줍니다.콘솔에서 'this.imgSrc'는 정의되지 않은 것으로 나타납니다. 아마도 내가 겪고있는 문제 때문일 것입니다. – rads89

+0

this.images가 아직 준비되지 않았기 때문에 해당 함수를 템플릿에서 직접 호출 할 수 없습니다. 구독 콜백이 호출되면 준비가 완료됩니다. 따라서 구독에서 함수를 호출해야합니다. 또는 템플릿에 필요하면 * .gif 상태를 추가해야합니다.이 상태는 this.images를 사용할 수있을 때 트리거를 구독 할 때 렌더링됩니다. – tibbus