Html Angular 6通过服务显示来自rest api的数据

Html Angular 6通过服务显示来自rest api的数据,html,angular,Html,Angular,我想在我的角度组件中显示来自RESTAPI的数据。我有一些来自此占位符url的数据:。我已经为它写了如下服务: 服务.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable, of } from 'rxjs';

我想在我的角度组件中显示来自RESTAPI的数据。我有一些来自此占位符url的数据:。我已经为它写了如下服务:

服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class nowService {

  serviceApiUrl: string = 'https://jsonplaceholder.typicode.com/posts';

  constructor(
    private http: HttpClient,

    ) { }

    public title: string;
    public id: number;  
    public body: string;
    public userId: number;

  public getAll() {
    return this.http.get(this.serviceApiUrl);
  }
}
component.ts文件

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
// Services 
import { nowService } from '../../services/now.service';


@Component({
  selector: 'app-service-incident',
  templateUrl: './service.component.html',
  styleUrls: ['./service.component.scss']
})
export class ServiceIncidentComponent implements OnInit {

  constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
      console.log('Result - ', data);
      console.log('data is received');
    })
  }
}

我希望能够在表格中显示这些数据。

您需要使用ngFor这样的功能

   <table class="table table-striped">
        <thead>
            <tr>
                <th>Title</th>
                <th>Id</th>
            </tr>
        </thead>
        <tbody>
           <tr *ngFor="let user of users">
            <td>{{user.id}}</td>
            <td><a routerLink="/detail/{{user.id}}">{{user.title}}</a></td>
           </tr>
        </tbody>
    </table>
</div>

什么不起作用?可能是重复的。你能分享你得到的错误吗?这里有一个有效的stackblitz:。很可能您忘记了将HttpClientModule添加到提供程序。是的,您必须声明变量并分配结果
export class ServiceIncidentComponent implements OnInit {
  users: any; //better to have your type
  constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
       this.users = data;
    })
  }
}