我正在尝试将本地JSON加载到我的组件中,但是我无法将服务中的值添加到我的组件中。我可以在服务中看到json数据,但在我的组件中未定义。有人看到我在这里做错了吗?感谢。
这是服务和组件中的console.log的SS
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); });
}
}
答案 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);
});
}
}