【问题标题】:Angular 6 display data from rest api via a serviceAngular 6通过服务显示来自rest api的数据
【发布时间】:2019-03-01 17:33:31
【问题描述】:

我想在我的角度组件中显示来自 rest api 的数据。我有一些来自这个占位符 url 的数据:https://jsonplaceholder.typicode.com/posts。我为它写了一个服务如下:

Service.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');
    })
  }
}

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

【问题讨论】:

标签: html angular


【解决方案1】:

使用 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>

在组件 ts 中。

您需要将响应分配回名为 users 的变量。比如,

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

【讨论】:

  • 是的,你必须声明变量并分配结果
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 2017-10-11
  • 1970-01-01
  • 2020-12-18
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多