Json 不传递数组的错误
我试着寻找解决这个问题的方法,但我找不到任何小于3岁或4岁的孩子,而且这些孩子也不能很好地解决我的问题。我知道错误是什么问题,但似乎无法找到它,尽管我将在下面的描述中说明我的总体想法: 我需要从以下格式的json元素数组生成菜单:Json 不传递数组的错误,json,angular,Json,Angular,我试着寻找解决这个问题的方法,但我找不到任何小于3岁或4岁的孩子,而且这些孩子也不能很好地解决我的问题。我知道错误是什么问题,但似乎无法找到它,尽管我将在下面的描述中说明我的总体想法: 我需要从以下格式的json元素数组生成菜单: { "body": [{ "coursename": "introto1", "course-lesson-name": "Welcome to One! " }, { "coursename": "in
{
"body": [{
"coursename": "introto1",
"course-lesson-name": "Welcome to One! "
}, {
"coursename": "introto2",
"course-lesson-name": "What is One?"
}, {
"coursename": "introto2",
"course-lesson-name": "What Can We do with One?"
}]
}
此响应来自AWS API网关,我已设置以下服务来处理该调用:
菜单.服务.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MenusService {
constructor(private http: HttpClient) { }
getLinks(){
return this.http.get('api address');
}
}
import { Component, OnInit } from '@angular/core';
import { MenusService } from './../menus.service';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
links;
constructor(private menusService: MenusService,) { }
ngOnInit(){
this.links = this.menusService.getLinks();
}
}
以下是使用服务的组件:
导航.component.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MenusService {
constructor(private http: HttpClient) { }
getLinks(){
return this.http.get('api address');
}
}
import { Component, OnInit } from '@angular/core';
import { MenusService } from './../menus.service';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
links;
constructor(private menusService: MenusService,) { }
ngOnInit(){
this.links = this.menusService.getLinks();
}
}
下面是组件视图:
navigation.component.html
<div>
<div class="col-sm-4" *ngFor="let links of links | async">
<a>{{links['course-lesson-name']}}</a>
</div>
</div>
我错过了什么
以下是供参考的错误:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
NgFor only supports binding to Iterables such as Arrays.
我打赌
this.links
解析为对象而不是数组
在您的ngOnInit中执行此操作:
ngOnInit(){
this.links = this.menusService.getLinks();
this.links.subscribe(data => console.log(data)); // ensure data here is an array and not an object with `{ body: [....] }`
}
如果是前面提到的对象,请在您的服务中尝试:
getLinks(){
return this.http.get('api address').pipe(
map(res => res.body),
);
}
您也可以在组件级别执行此操作,但只需确保在数组上获得句柄,而不是在*ngFor
的对象上