我有一个服务,它使用GET请求从休息调用(firebase)获取json数据。我试图在中间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;
}
)
}
}
中等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')
);
}
中等box.component.html
<ul class="list-group" *ngFor="let job of jobs">
<li class="list-group-item">{{ job.name }}</li>
</ul>
答案 0 :(得分:0)
作业,未在您的组件中定义,而是在您的Twitter服务中定义。
您需要twitterservice才能从中间的box.component.ts访问作业,以便在您的html中使用它。
因此您可以将其分配给本地作业,或使用twitterservice.jobs.name
答案 1 :(得分:0)
试试这些
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>
答案 2 :(得分:0)
这是一个来自newby的答案,所以请耐心等待。我也遇到过这个问题,但是当我使用异步方法并且不打扰订阅时,问题就消失了。
function PassInputDataToServer(id, inputData)
{
alert(document.URL + "/" + PassDataToServer);
$.ajax({
type: "POST",
url: document.URL + "/" + PassDataToServer,
data: { "id": "'" + id + "'", "clientData": "'" + inputData + "'" },
contentType: 'application/json; charset=utf-8',
dataType: "text",
success: function (result) { transferStatus.push(result); },
error: function (result) { transferStatus.push("failed"); },
complete: function (result) { transfersCompleted++; }
});
}
@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();
}
注意:在Angular 5中,您不再在observable(no <ul class="list-group" *ngFor="let job of jobs | async">
<li class="list-group-item">{{ job.name }}</li>
</ul>
)的响应中调用.json。