首页 > 解决方案 > Angular:错误:将 ngFor 绑定到数组(管道参数无效)

问题描述

请注意,关于同一错误的其他问题没有帮助,因为我使用不同的方式来获取数据。

我想从 API 获取 JSON 数据并使用 Angular 在页面中显示它们。我的 json 数据由 faqlist 中的 faq 数组组成。我想从数组的每个元素中获取 title 和 id 并使用 ngFor 在页面中显示它们指示。

我已成功从 API 获取数据。

我正在尝试使用 ngFor 指令绑定它,但出现以下错误。如果有任何机构可以帮助我,我不知道我做错了什么。下面是我的代码和错误。

                                  **ERROR**

错误 JSON数据 在此处输入图像描述

输出(this.faqq) 在此处输入图像描述

在此处输入图像描述

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});
  }

标签: angularangularjs-directive

解决方案


试试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管道需要一个,这Observablepipe()返回的。在您的原始代码中,您将数组分配给faqq,而不是Observable数组。


推荐阅读