我想在我的角度组件中显示来自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');
})
}
}
我希望能够在表中显示此数据。
答案 0 :(得分:3)
您需要使用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中。
您需要将响应分配回名为用户的变量。像
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;
})
}
}