2017-09-01 51 views
0

這可能只是我,但我真的有一個糟糕的時期角文檔。例如,我想了解如何讀取(在其上運行循環並從中拖出一些數據)JSON文件,並且我找到了Angular文檔的這個鏈接:https://angular.io/guide/http製作的JSON數據的請求與角2

他們正在發佈下面的代碼,但不要說在它應該去(到什麼文件):

@Component(...) 
export class MyComponent implements OnInit { 

    results: string[]; 

    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 

    ngOnInit(): void { 
    // Make the HTTP request: 
    this.http.get('/api/items').subscribe(data => { 
     // Read the result field from the JSON response. 
     this.results = data['results']; 
    }); 
    } 
} 

附註:我把我的JSON文件資產文件夾內,我想在幾個組件從它使用的數據。

附註二:我真的很感激着如何處理文檔,也許我失去了一些東西你的幫助?新手很難理解到底在哪裏。

感謝

+0

@wprzechodzen,感謝您嘗試編輯,但'angularjs'比'angular'更多的用戶。在不刪除'angularjs'的情況下進行編輯,我會很高興地批准它。您在編輯說,'問題的角度連接 - 不AngularJS' - 你能告訴我什麼區別? 0_o – mazori

回答

0
// version without map 

    @Component(...) 
export class MyComponent implements OnInit { 

    results: string[]; 

    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 

    ngOnInit(): void { 
    // Make the HTTP request: Add **.json** if it's a json file 
    this.http.get('/api/items.json').subscribe(data => { 
     // Read the result field from the JSON response. 
     this.results = data['results']; 
    }); 
    } 
} 

// with map 
import 'rxjs/add/operator/map' 

@Component(...) 
export class MyComponent implements OnInit { 

    results: string[]; 

    // Inject HttpClient into your component or service. 
    constructor(private http: HttpClient) {} 

    ngOnInit(): void { 
    // Make the HTTP request: 
    this.http.get('/api/items.json') 
    .map((data) => { 
     return data.json(); 
    }) 
    .subscribe((data) => { 
    this.results = data['results'];  
    }); 
    } 
} 
+0

應該在哪裏這個去的,拉詹?什麼文件? – mazori

+0

這應該放在您正在處理上述代碼的同一個文件中。你可以請,澄清,如果你正在請求API與JSON文件或API請求只。 如果你試圖從服務器上傳.json文件只需添加以.json在您的API請求。 –

+0

我甚至不確定這是一個API請求。我只是想從JSON文件中獲取數據。我現在所擁有的是一個默認組件 - 根源。我應該把這個代碼放在'app.component.ts'嗎?至於現在,它有這樣的代碼:'export class AppComponent {0} {title ='app'; }' – mazori