angular - Angular:错误:将 ngFor 绑定到数组(管道参数无效)
问题描述
请注意,关于同一错误的其他问题没有帮助,因为我使用不同的方式来获取数据。
我想从 API 获取 JSON 数据并使用 Angular 在页面中显示它们。我的 json 数据由 faqlist 中的 faq 数组组成。我想从数组的每个元素中获取 title 和 id 并使用 ngFor 在页面中显示它们指示。
我已成功从 API 获取数据。
我正在尝试使用 ngFor 指令绑定它,但出现以下错误。如果有任何机构可以帮助我,我不知道我做错了什么。下面是我的代码和错误。
**ERROR**
faq-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs";
import { faqService } from "../faq.service";
import { Faq} from "../faq";
import { Router } from '@angular/router';
import { Token } from '../token';
@Component({
selector: 'app-faq-list',
templateUrl: './faq-list.component.html',
styleUrls: ['./faq-list.component.css']
})
export class faqListComponent implements OnInit {
token:Token;
faqq:Observable<Faq[]>;
constructor(private faqService: faqService,
private router: Router) {
}
ngOnInit() {
this.reloadData();
}
reloadData() {
this.faqService.getToken()
.subscribe(res => {
this.token=new Token(res);
this.faqService.getfaqList(this.token.access_token)
.subscribe(res => {
this.faqq=res.faqList.faq.map((faq:any)=> new Faq(faq));
console.log(this.faqq);
debugger;
})
})
}
}
常见问题列表.component.html
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Faq List</h2>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Id :</th>
<th>Title :</th>
<th>excerpt :</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let faq of faqq |async">
<td>{{faq.id}}</td>
<td>{{faq.title}}</td>
<td>{{faq.excerpt}}</td>
</tr>
</tbody>
</table>
</div>
</div>
常见问题服务.ts
getfaqList(token_t:String):Observable<any>{
let body="";
let header = new HttpHeaders()
.set('Access-Control-Allow-Origin', '*')
.set('Accept','application/json')
.set('Content-Type', 'application/xml')
.set('Authorization', 'Bearer ' + token_t);
return this.http.post('url',body, {headers: header});
}
解决方案
试试pipe
这样:
reloadData() {
this.faqService.getToken()
.subscribe(res => {
this.token=new Token(res);
this.faqq = this.faqService.getfaqList(this.token.access_token)
.pipe(map(res => res.faqList.faq.map((faq: any) => new Faq(faq)) ));
})
})
}
| async
管道需要一个,这Observable
是pipe()
返回的。在您的原始代码中,您将数组分配给faqq
,而不是Observable
数组。
推荐阅读
- python - 两个不同的数据库连接同时 Python
- android - Fragment Android 中的 DatePicker 未显示
- jquery - 如何使用 jquery.ui.combify 设置选择对象的宽度
- javascript - 让 Discord Bot 接收文件并将内容发送到频道
- angular - Angular 5 - ng 测试 - 请包括“BrowserAnimationsModule”或“NoopAnimationsModule”
- python - 计算一个月有多少天
- graphics - 将 GeometryModel3D 显示为点云的最简单方法是什么?(HelixToolkit / SharpDX / DirectX)
- ios - 如何隐藏 Tabbarcontroller 的第一个视图控制器并直接转到下一个控制器但应在底部显示标签栏项目
- c# - asp.net core automapper ViewModel to Model
- javascript - 由 javascript 数组操作的 HTML 输入