2017-04-11 48 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