Angular jquery 数据 table 问题/ngFor

Angular jquery data table issue / ngFor

我有一个与使用 ngFor 指令查询数据 tables 相关的问题, 如果我将 jquery data tables 与静态数据一起使用,它工作正常,但是当我使用 data table 和 *ngFor 指令从 http / api 服务获取数据时,一旦我第一次渲染页面,我看到了一个完美的结果,如果我路由到另一个页面并返回,我看到没有找到数据消息,同时所有 Table 数据和数据 table 功能类似分页、过滤、搜索都不起作用,我应该重新刷新页面来解决这个问题!!

请协助解决该问题?!!

import { Component, OnInit } from '@angular/core';
import { TestserviceService } from '../services/testservice.service';
declare var $: any;
declare var jQuery: any;


@Component({
  selector: 'Test',
  templateUrl: './test.html'
})
export class Test implements OnInit {
  posts: any[];
  constructor(public mytestservice: TestserviceService) { 

    this.mytestservice.getposts().subscribe(response =>{
      this.posts = response.json();
    });

  }

  ngOnInit() {

    $(function(){
      $('#posts').DataTable({
        responsive: true
      });
    });
  }
}
<div class="card-body">
        <table class="table table-hover" id="posts" width="100%">
            <thead>
                <tr>
                    <th>SEQ </th>
                    <th>User ID</th>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let post of posts">
                    <td>###</td>
                    <td>{{post.userId}}</td>
                    <td>{{post.id}}</td>
                    <td>{{post.title}}</td>
                    <td>{{post.body}}</td>
                </tr>
            </tbody>
        </table>
    </div>

试试这段代码-

constructor(public mytestservice: TestserviceService) { 

    this.mytestservice.getposts().subscribe(response =>{
      this.posts = response.json();
      $('#posts').DataTable({
        responsive: true
      });
    });

  }

  ngOnInit() { }

这就是解决方案

  ngOnInit() {
    this.mytestservice.getposts().subscribe(response =>{
      this.posts = response.json();
      $(function(){

        $('#posts').DataTable({
          responsive: true
        });
      });
    });
  }