2017-04-11 69 views
1

我試圖將本地JSON加載到我的組件中,但我無法從我的服務中獲取值到我的組件中。我可以看到服務中的json數據,但它在我的組件中未定義。有人看到我在這裏做錯了嗎?謝謝。Angular中的異步數據處理

這裏是的console.log在兩個服務和成分的SS

Console.log in service and component

interfaces.json

{ 
    "interfaces": { 
    "eth" : {"name" : "eth"}, 
    "lte" : {"name" : "lte"}, 
    "wlc" : {"name" : "wlc"}, 
    "wlap" : {"name" : "wlap"} 
    } 
} 

interfaces.service.ts

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 

@Injectable() 
export class Interfaces { 

    constructor(public http: Http) {}; 

    public getData() { 
    return this.http.get('/assets/interfaces.json') 
    .map((res) => {res.json(); console.log(res); }); 
    }; 
} 

interfaces.component.ts

import { Component, OnInit } from '@angular/core'; 
import { Interfaces } from './interfaces.service'; 
import { Observable } from 'rxjs/Rx'; 

@Component({ 
    selector: 'interfaces', 
    providers: [ 
    Interfaces 
    ], 
    template: ` 
    <ul *dropdownMenu class="dropdown-menu" role="menu"> 
     <li *ngFor="let interface of interfaces | async" role="menuitem"> 
     <a [routerLink]=" ['./interfaces/eth'] "routerLinkActive="active" 
     [routerLinkActiveOptions]= "{exact: true}" class="dropdown-item" href="#"> 
     {{interface.name}}Main Ethernet 
     </a> 
     </li> 
    </ul> 
    `, 
}) 

export class InterfacesComponent implements OnInit { 

    constructor(public interfaces: Interfaces) {} 

    public ngOnInit() { 
    this.interfaces.getData().subscribe((data) => { this.data = data; console.log(data); }); 

    } 
} 

回答

3

的原因,它的undefined是,你不必返回map內的響應不是地圖不起作用..

.map((res) => {console.log(res); return res.json(); }); // missing return here 

或不帶括號:

.map((res) => res.json()); 
1

我不知道什麼是錯誤的,因爲我是新來angular2,但是這對我的作品。

interfaces.service.ts

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 

@Injectable() 
export class Interfaces { 

    constructor(public http: Http) {}; 

    public getData() { 
    return this.http.get('/assets/interfaces.json'); 
    } 
} 

interfaces.component.ts

import { Component, OnInit } from '@angular/core'; 
import { Interfaces } from './interfaces.service'; 
import { Observable } from 'rxjs/Rx'; 

export class InterfacesComponent implements OnInit { 

    constructor(public interfaces: Interfaces) {} 

    public ngOnInit() { 
    this.interfaces.getData().subscribe((data) => { 
      this.data = data; 
      console.log(data); 
    }); 
    } 
} 
+0

嘿!你是對的,沒有.map()它的作品。我想我只需在組件或服務中使用它一次,否則它會弄亂數據......感謝您的快速響應! – LordStryker