我有一个服务,它使用 GET 请求从 rest 调用 (firebase( 获取 json 数据。我正在尝试在middle-box.component上显示响应数据.html
修复此错误的任何建议或解决方案:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
twitter.service.ts
@Injectable()
export class TwitterService {
constructor(private http: Http) {}
getJobs() {
var jobs = {}
console.log('Twitter Service Called !');
return this.http.get('https://dmm-db.firebaseio.com/jobs.json')
.map(
(response: Response) => {
var data = response.json();
var jobs = [], item;
for (var type in data) {
console.log(type);
item = {};
item.name = type;
jobs.push(item);
}
console.log(jobs);
return jobs;
}
)
}
}
middle-box.component.ts
@Component({
selector: 'app-middle-box',
templateUrl: './middle-box.component.html',
styleUrls: ['./middle-box.component.css']
})
export class MiddleBoxComponent implements OnInit {
constructor(private twitterService: TwitterService) {
twitterService.getJobs()
.subscribe(
(jobs: any[]) => this.jobs = jobs,
(error) => console.log('Error: '+ error),
() => console.log('Completed')
);
}
middle-box.component.html
<ul class="list-group" *ngFor="let job of jobs">
<li class="list-group-item">{{ job.name }}</li>
</ul>
试试这些
export class MiddleBoxComponent implements OnInit {
private jobs: any[];
private isLoading: boolean = false;
constructor(private twitterService: TwitterService) { }
ngOnInit() {
this.isLoading = true;
this.twitterService.getJobs()
.subscribe((jobs: any[]) => {
this.jobs = jobs,
this.isLoading = false;
},
(error: any[]) => console.log('Error: ' + error),
() => console.log('Completed')
);
}
使用 ngOnInit(( 调用你的 API 而不是构造函数。 这是一个很好的做法。
<ul class="list-group" *ngIf="!isLoading" *ngFor="let job of jobs" >
<li class="list-group-item" > {{ job.name }}</li>
< /ul>
作业不是在你的组件中定义的,而是在你的Twitter服务中定义的。
你需要twitterservice来访问middle-box.component.ts的作业,以便在你的html中使用它。
因此,您可以将其分配给本地作业,或使用 twitterservice.jobs.name
这是一个来自新手的答案,所以请持保留态度。我也遇到了这个问题,但是当我使用异步方法并且不打扰订阅时,问题就消失了。
@Component({
selector: 'app-middle-box',
templateUrl: './middle-box.component.html',
styleUrls: ['./middle-box.component.css']
})
export class MiddleBoxComponent implements OnInit {
public jobs;
constructor(private twitterService: TwitterService) {
this.jobs = twitterService.getJobs();
}
<ul class="list-group" *ngFor="let job of jobs | async">
<li class="list-group-item">{{ job.name }}</li>
</ul>
注意:在 Angular 5 中,您不再在可观察量(无var data = response.json()
(中的响应上调用 .json。