2017-10-21 155 views
-4

我的API正在獲取JSON響應。現在,我試圖只在一個組件中顯示它,以便了解和觀察數據如何傳輸和顯示,以便稍後構建它。無法顯示API響應

由於某種原因,即使我的組件正在工作(我保留其他一些內容以跟蹤顯示與否),我也無法顯示任何內容。

任何建議我在做什麼錯誤或如何嘗試使它工作?我已經用完了想法,而且我的互聯網搜索功能非常強大。

contact.service.ts

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/Http'; 
import { Observable } from 'rxjs/Observable'; 
import { map } from "rxjs/operator/map"; 
import { environment } from '../environments/environment'; 
import { IContact } from './icontact'; 
import './rxjs-operators'; 

const API_URL = environment.apiUrl; 

@Injectable() 
export class ContactService { 

    constructor(private http: Http) { } 

    public getContacts(): Observable<IContact[]> { 
     return this.http.get(API_URL) 
      .map(response => <IContact[]>response.json()); 
    } 
} 

contact.component.ts

import { Component, OnInit } from '@angular/core'; 
import { ContactService } from '../contact.service'; 
import { Http, Response } from '@angular/Http'; 
import { IContact } from '../icontact'; 

@Component({ 
    selector: 'app-contact', 
    templateUrl: './contact.component.html', 
    styleUrls: ['./contact.component.css'], 
    providers: [ContactService] 
}) 

export class ContactComponent implements OnInit { 

    private contactlist: IContact[]; 

    constructor(private contactService: ContactService) { 
    } 

    public ngOnInit() { 
     this.contactService.getContacts().subscribe(
      (contacts) => { this.contactlist = contacts; }, 
      (error) => { console.log(error); } 
     ); 
    } 
} 

contact.component.html - 如果我得到它的權利,下面的模板應該能夠從顯示我的東西API,但它回來了。

<div *ngFor="let contact of contacts"> 
{{contact}} 
</div> 

回答

1

您的組件沒有一個叫contacts場,讓您的ngFor將永遠不會有什麼遍歷。

嘗試將其更改爲

<div *ngFor="let contact of contactList"> 
{{contact}} 
</div> 
+0

關閉 - 但不完全。我沒有看到自己的東西 - contactlist沒有contactList ;-)我以前嘗試contactList,它沒有工作,我認爲我做錯了什麼,事實證明這是一個錯字。傻我。謝謝! – WAR