angular2 ngFor not working while fetching data from api on ngOnInit()

后端 未结 6 517
别跟我提以往
别跟我提以往 2021-01-13 03:42

comment.component.ts:

import { Component, OnInit } from \'@angular/core\';
import { Router} from \'@angular/router\'
import { Comment } from         


        
6条回答
  •  没有蜡笔的小新
    2021-01-13 04:22

     I have found a solution of my issue using Zone and promise.
     below is the update code of the "comments.component.ts".
     by using zone.run(), I am able to bind data with HTML when
     "comments.component" is loaded.    
    

    Is this a correct way to bind data with HTML if data is coming using api?

        import { Component, OnInit, NgZone } from '@angular/core';  //NgZone *
        import { Router} from '@angular/router'
        import { Comment } from 'comment entity path'
        import {CommentService} from 'comment service path'
        import { Observable } from 'rxjs/Observable';
        import 'rxjs/add/operator/toPromise'   // *
        @Component({
            template: `
    • {{item.Name}}
    ` }) export class CommentComponent implements OnInit { comments: comment[]=[]; // * constructor(private router: Router, private commentService: CommentService, private zone: NgZone) { } ngOnInit() { this.zone.run(() => { this.getComments().toPromise().then((data) => { this.comments= data || []; }); }) } getComments() { return this.commentService.getComments(); } }

提交回复
热议问题