首页 > 解决方案 > 在 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>

我错过了什么?

标签: htmlangulartypescriptangular-templateweb-api-testing

解决方案


推荐阅读