2017-11-24 12 views
0

저는 앵귤러 2로 하이 차트를 사용합니다. 정적 데이터를 사용하면 차트가 예상대로 렌더링되지만, http.get 요청의 데이터를 서비스를 사용하고 구독을 사용하여 렌더링하지 않는 구성 요소로 가져옵니다. 대신 빈 차트가 반환됩니다. console.log에서 데이터가 예상대로 구성 요소에 반환되고 있는지 확인할 수 있습니다. 내가 뭘 잘못하고 있는지 모르겠다. 아래는 관련 코드입니다. 미리 감사드립니다.http.get의 데이터를 사용할 때 하이 차트가 각도 2로 렌더링되지 않습니다.

서비스

const API_URL = 'https://api.blockchain.info/price/index-series?base=btc&quote=USD&start=1503145039&scale=7200'; 

@Injectable() 
export class BitcoinPriceService { 

loadstate: boolean; 

stateChange: Subject<boolean> = new Subject<boolean>(); 

moneyArray = []; 

moneyChange: Subject<any> = new Subject<any>(); 

private getArray(): void { 
// this.moneyChange.next(this.moneyArray); 
} 

constructor(private http: Http) { 
    this.loadstate = false; 
} 

private showLoader(): void { 
    this.loadstate = true; 
    this.stateChange.next(this.loadstate); 
} 

private hideLoader(): void { 
    this.loadstate = false; 
    this.stateChange.next(this.loadstate); 
} 

    getData(url = API_URL) { 
    this.showLoader(); 
    return this.http.get(API_URL) 
     .subscribe((res: Response) => { 
      let results = this.moneyArray; 
      let obj = res.json(); 
      obj.forEach(
       function (o: any) { 
        results.push(o); 
       } 
      ); 
     }) 
// .error(err => { 
     // console.error('handling error within getData()', err); 
     // const fakeData = [{ name: 'no prices could be retrieved' }]; 
     // return Observable.of(fakeData); 
     // }) 
     // .finally(() => { 
     //  this.getArray(); 
//  this.hideLoader(); 

//  console.log('hideloader', this.loadstate); 
//  console.log(this.moneyArray); 
// }); 
} 

} 

구성 요소 JSON 데이터가 moneyArray에 반환하는 방법 이것은

export class ChartComponent implements OnInit { 

priceData: Subscription; 

loadstate: boolean; 
subscription: Subscription; 

moneyArray = []; 

constructor(bs: BitcoinPriceService) { 
    console.log(bs); 
    this.priceData = bs.getData(); 
    this.loadstate = bs.loadstate 
    this.subscription = bs.stateChange.subscribe((value) => { 
     this.loadstate = value; 
    }); 



    console.log('moneyArray', this.moneyArray = bs.moneyArray); 

    console.log('priceData', this.priceData); 
    console.log('loadstate', this.loadstate); 
} 


private data = [ 
    { 
     name: 'USA', 
     data: this.moneyArray 
    }, 
    { 
     name: 'USSR/Russia', 
     data: this.moneyArray, 
    }]; 

ngAfterViewInit() { 
    this.renderChart(); 
} 

renderChart(){ 
    jQuery('#container').highcharts({ 
     chart: { 
      type: 'area' 
     }, 
     title: { 
      text: 'Bitcoin Price' 
     }, 
     subtitle: { 
      text: 'Source: thebulletin.metapress.com' 
     }, 
     xAxis: { 
      allowDecimals: false, 
      labels: { 
       formatter: function() { 
        return this.value; 
       } 
      } 
     }, 
     yAxis: { 
      title: { 
       text: 'Nuclear weapon states' 
      }, 
      labels: { 
       formatter: function() { 
        return this.value/1000 + 'k'; 
       } 
      } 
     }, 
     tooltip: { 
      pointFormat: '{series.name} produced <b>{point.y:,.0f}</b>' + 
         '<br/>warheads in {point.x}' 
     }, 
     plotOptions: { 
      area: { 
       pointStart: 1940, 
       marker: { 
        enabled: false, 
        symbol: 'circle', 
        radius: 2, 
        states: { 
         hover: { 
          enabled: true 
         } 
        } 
       } 
      } 
     }, 
     series: [{ 
      data: this.data, 
      name: 'Value Type Description' 
     }] 
    }); 
} 

ngOnDestroy() { 
    //prevent memory leak when component destroyed 
    this.subscription.unsubscribe(); 
} 
} 

. enter image description here

+0

당신은 동시성을 이해할 필요가있다() 별도의 함수 내에서 API 호출을 작성하고 ngOnInit에 전화를 더 좋을 것이다. 건배를 토스터에 넣은 직후에 건배하려고합니다. 그건 안돼. 토스터가 준비가되었다고 말하면 토스터에서 토스트를 가져와야합니다. 서비스 내에서 가입을 중지하십시오. 귀하의 서비스는 Observable을 반환해야합니다. 구성 요소에서 Observable을 구독해야합니다. 그런 다음 관찰 대상이 비동기 적으로로드 된 데이터를 제공 할 때 호출되는 구독 콜백, 데이터를 사용할 수 있으며 해당 데이터로 차트를 작성할 수 있습니다. 'service.getData(). subscribe (data => buildChartWithData (data))'). –

+0

감사합니다. 그러나 이것은 완전히 명확하지 않습니다. 그래서 내 컴포넌트를 컴포넌트 안에 넣어야하지만, "buildChartWithData (data)"는 무엇을 나타내는가? – London804

+0

observable 이벤트에서 얻은 데이터로 차트를 만드는 코드 –

답변

0

'rxjs/add/operator/map'을 사용해야한다고 생각합니다.

import 'rxjs/add/operator/map'; 

constructor(bs: BitcoinPriceService, private zone: NgZone) { 
    console.log(bs); 
    this.priceData = bs.getData().map(resp => { 
    //You can init your chart here 
    }; 
); 
    this.loadstate = bs.loadstate 
    this.subscription = bs.stateChange.subscribe((value) => { 
    this.loadstate = value; 
    }); 
} 

또한