我正在开展一个角度4项目并且我提供了一个服务来从网址获取json,service.ts看起来像这样:
import {Injectable} from '@angular/core';
import {Http , Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class EventsService{
constructor(private http:Http){
}
private url: string = "http://urlofmyjson/events";
getEvents() {
return (
this.http.get(this.url).map((response: Response) => response.json())
)
}
}
json的内容如下所示:
{
"events":[
{
"title":"event1"
"location":"location1"
"date":"date1"
},
{
"title":"event2"
"location":"location2"
"date":"date2"
},
{
"title":"event3"
"location":"location3"
"date":"date3"
},
]
}
在我的组件中我有这个:
import { Component, OnInit } from '@angular/core';
import {EventsService} from './conciertos.service';
@Component({
selector: 'app-events',
templateUrl: './events.component.html',
styleUrls: ['./events.component.scss']
})
export class EventsComponent implements OnInit {
constructor(private EventsService: ConciertosService) { }
events = []:
ngOnInit() {
this.EventsService.getEvents().subscribe( ResponseEvents => this.events=ResponseEvents);
}
}
然后我想用* ngFor迭代json的每个事件,但是当json检索一个包含事件对象的内部数组的对象时,我无法迭代它,因为它会抛出一个错误。
如何将服务的响应放在字符串类型变量中以调用并使用* ngFor进行迭代?