2016-11-04 179 views
1

我想在角2中從外部API發出請求。 我想管理2個文件中的數據請求並將結果顯示爲json。HTTP請求角2

我的數據輸出部分看起來是這樣的:

import {Component} from '@angular/core' 
import {DataService} from './datavisualisation.service' 

    @Component({ 
     selector: 'app-datavisualisation-output', 
     template: ` 
     ` 
    }) 
    export class DatavisualisationOutput { 
     constructor(dataservice: DataService) { 
      dataservice.data 
       .subscribe(
        data => this.data = data, 
        console.error, 
        () => console.log('Look at this:' + data) 
       ); 
     } 

    } 

我對服務第二個文件是這樣的:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class DataService { 
    constructor(http:Http) { 
     this.data = http.get('http;//...API') 
      .map(response => response.json()); 
    } 
} 

...但控制檯顯示以下錯誤:

components/datavisualisation/dataservices/datavisualisation.output.service.ts:12:26 
Property 'data' does not exist on type 'DataService'. 
components/datavisualisation/dataservices/datavisualisation.output.service.ts:14:29 
Property 'data' does not exist on type 'DatavisualisationOutput'. 
components/datavisualisation/dataservices/datavisualisation.output.service.ts:16:43 Cannot find name 'data'. 
components/datavisualisation/dataservices/datavisualisation.service.ts:8:13 
Property 'data' does not exist on type 'DataService'. 

我在做什麼錯在這裏?

回答

2

應定義data財產上的DatavisualisationOutput組件:

export class DatavisualisationOutput { 

    public data: any; //this one 

    constructor(dataservice: DataService) { 
     dataservice.data 
      .subscribe(
       data => this.data = data, 
       console.error, 
       () => console.log('Look at this:' + data) 
      ); 
    } 

} 

,並在你的DataService

@Injectable() 
export class DataService { 

    public data: any; 

    constructor(http:Http) { 
     this.data = http.get('http;//...API') 
      .map(response => response.json()); 
    } 
} 

DatavisualisationOutput ...只是..總是定義您訪問任何財產this

0

由於@PierreDuc已經表示您應該在組件類中定義該變量,以使其在Class上下文中可用。

此外,您應該在服務內部創建一個負責數據的方法。只需從另一個組件調用相同的方法,它將返回上次檢索到的數據。

代碼

@Injectable() 
export class DataService { 
    data: any; 
    constructor(http:Http) { 
    } 

    getData(){ 
     if(this.data) return Observable.of(this.data) 
     else 
      return http.get('http;//...API') 
      .flatMap(response => { 
       this.data = response.json(); 
       return Observable.of(this.data) 
      ); 
    } 
} 

組件

export class DatavisualisationOutput { 
    myData: any; 
    constructor(private dataservice: DataService) { 
     dataservice.data 
      .subscribe(
       data => this.data = data, 
       console.error, 
       () => console.log('Look at this:' + data) 
      ); 
    } 
    ngOnInit(){ 
     dataservice.getData().subscribe(
      data => myData = data 
     ) 
    } 
}