我試圖將本地JSON加載到我的組件中,但我無法從我的服務中獲取值到我的組件中。我可以看到服務中的json數據,但它在我的組件中未定義。有人看到我在這裏做錯了嗎?謝謝。Angular中的異步數據處理
這裏是的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); });
}
}
嘿!你是對的,沒有.map()它的作品。我想我只需在組件或服務中使用它一次,否則它會弄亂數據......感謝您的快速響應! – LordStryker