html - 在 Angular 中使用在线 API
问题描述
我正在学习 Angular 并尝试使用在线 Web API,其中有 app.module.ts、服务文件、名为 comments 的模型、app.component.ts 和 app.component.html 文件
,我试图在其中显示帖子我的浏览器来自 https://jsonplaceholder.typicode.com/posts/1/comments URL 的在线 Web API。
我的代码编译成功,但在浏览器中没有显示任何数据,也找不到任何错误。我在 Angular 8/9 中工作。我的代码如下。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FreeapiService } from './services/freeapi.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [FreeapiService],
bootstrap: [AppComponent]
})
export class AppModule { }
freeapi.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FreeapiService {
constructor(private http: HttpClient) { }
getComments(): Observable<any> {
return this.http.get("https://jsonplaceholder.typicode.com/posts/1/comments")
}
}
评论类
export class Comments {
postId: number;
id: number;
name: string;
email: string;
body: string;
}
应用组件.ts
import { Component, OnInit } from '@angular/core';
import { FreeapiService } from './services/freeapi.service';
import { Comments } from './classes/comments';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular-apicall';
constructor(private _freeApiService: FreeapiService) { }
istComments: Comments[];
ngOnInt() {
this._freeApiService.getComments()
.subscribe
(
data => {
this.istComments = data;
}
);
console.log("This is working");
}
}
这是我的app.component.html文件,我想在表格中显示数据,但只显示标题
<table>
<tr>
<th>ID</th>
<th>Post Id</th>
<th>Name</th>
<th>Email</th>
<th>Body</th>
</tr>
<tr *ngFor="let com of istComments">
<td>{{com.id}}</td>
<td>{{com.postId}}</td>
<td>{{com.name}}</td>
<td>{{com.email}}</td>`enter code here`
<td>{{com.body]}</td>
</tr>
</table>
我错过了什么?
解决方案
推荐阅读
- php - 我想返回 JSON 类型但 PHP 什么也不返回
- mongodb - 从 mongodb 导出文件
- r - 有没有办法在 mutate 中包含 Groupby
- php - 将 HTML 链接添加到 PHP 消息数组
- rust - 如何从返回异步的 Vec 闭包中加入_all?
- google-apps-script - Quandl API 在 Google appscript 上返回 HTML 响应
- javascript - 画布绘制触摸未绘制
- python-3.x - 具有多个输入的 Python 字典列表搜索
- node.js - 需要帮助以解决 npm start 错误
- jaxb - 通过 WebServiceGatewaySupport 编组失败并出现 JAXBException: class
在此上下文中也不知道它的任何超类