【问题标题】:I am getting Data in Console Using Angular but I can't render it in html我正在使用 Angular 在控制台中获取数据,但我无法在 html 中呈现它
【发布时间】:2018-12-02 21:44:02
【问题描述】:

这是我的 Page-datail.component.ts

export class PageDetailComponent implements OnInit {

  private apiUrl="http://localhost:3000/pages"

  pages={};
  // data={};

  constructor(private route:ActivatedRoute,private page:PageService,private router: Router,private http:Http) { }

  ngOnInit() {
    this.getpage(this.route.snapshot.params['title']);
    // this.getPages();
    // this.getData();

  }
  getpage(title) {
    this.page.getPage(title)
      .subscribe(pages => {
        console.log(pages);
        this.pages = pages;
      }, err => {
        console.log(err);
      });
  }

这是我在控制台中得到的响应。我收到此对象对象错误,它无法在 html 中呈现它。

<a *ngFor="let p of pages" class="list-group-item list-group-item-action">
  {{p.title}}
</a>

This is the response I am getting in the console

【问题讨论】:

  • pages 需要是一个数组
  • ngFor 指令适用于数组而非对象。 this.pages 是一个对象而不是数组,所以是错误的。
  • 那我该怎么做才能显示数据
  • 如果你得到一个数组作为响应,定义为数组,如 pages = [];但是根据您的屏幕截图,您似乎得到了一个对象作为响应。把 {{pages.title}} 放到 ngFor 外面就可以看到 'home'

标签: node.js angular api angular6


【解决方案1】:

试试这个,

export class PageDetailComponent implements OnInit {

  private apiUrl="http://localhost:3000/pages"

  pages=[];
  // data={};

  constructor(private route:ActivatedRoute,private page:PageService,private router: Router,private http:Http) { }

  ngOnInit() {
    this.getpage(this.route.snapshot.params['title']);
    // this.getPages();
    // this.getData();

  }
  getpage(title) {
    this.page.getPage(title)
      .subscribe(page => {
        console.log(page);
        this.pages.push(page);
      }, err => {
        console.log(err);
      });
  }

【讨论】:

    【解决方案2】:

    原因是我得到这个是我在对象而不是数组中返回我的数据我这样做就像

    {{pages.title}} 
    

    你可以做到这样的对象

    pages:any={};   //For Objects
    page:any=[];    //For Arrays
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2018-09-09
      • 2019-06-10
      • 2022-08-03
      相关资源
      最近更新 更多