Angular中的异步数据处理

时间:2017-04-11 11:24:28

标签: json angular asynchronous service components

我正在尝试将本地JSON加载到我的组件中,但是我无法将服务中的值添加到我的组件中。我可以在服务中看到json数据,但在我的组件中未定义。有人看到我在这里做错了吗?感谢。

这是服务和组件中的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); });

  }
}

2 个答案:

答案 0 :(得分:4)

undefined的原因是您没有在map内回复您的回复,而不是该地图无效...

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

或没有括号:

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

答案 1 :(得分: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);
    });
  }
}