【问题标题】:Fetched data not rendering in Angular获取的数据未在 Angular 中呈现
【发布时间】:2023-02-02 22:15:38
【问题描述】:

我正在尝试使用 Angular 从 API 获取数据。我可以在控制台日志中看到数据已获取,但数据未呈现在页面上。帮助表示赞赏。 这是我的代码:

应用程序组件.html

<p>{{data.Name}}</p>
<p>{{data.Habitat}}</p>
<p>{{data.Status}}</p>

应用程序组件.ts

import { ApiserviceService } from './Service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'apidata';
 data:any;
 constructor(private _apiservie:ApiserviceService){}

ngOnInit(){
 this._apiservie.getdata().subscribe(res=>{
   this.data=res;
   console.log(res)
 })

应用程序模块.ts

import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   HttpClientModule,
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

服务.ts

import { Injectable } from '@angular/core';

@Injectable({
   providedIn: 'root'
})
export class ApiserviceService {
constructor(private _http:HttpClient){}
   getdata(){
return this._http.get('https://mocki.io/v1/8f823c35-8ae8-4fb5-a84b-cf7dce59c7a7');
   }
}

【问题讨论】:

  • 嗨,Link,能否请您与我们分享控制台,看看您面临什么样的问题
  • API 返回一个数组,因此您应该将代码包装在 *ngFor 周围。类似于:<div *ngFor="let item of data"> <p>{{item.Name}}</p> <p>{{item.Habitat}}</p> <p>{{item.状态}}</p> </data>
  • @Lorenzo 请发布作为答案
  • 我需要等待 30 分钟,因为 Stackoverflow 的某个人决定这是规则:/

标签: javascript angular api


【解决方案1】:

应用程序组件.ts

import { ApiserviceService } from './Service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'apidata';
 data:any;
 constructor(private _apiservie:ApiserviceService){}

ngOnInit(){
  this.getinfo()
 
}
getinfo(){
this._apiservie.getdata().subscribe(res=>{
  this.data=res;
  console.log(res)
})
}
}

应用程序组件.html

<div *ngFor="let item of data">
    <p>{{item.Name}}</p>
     <p>{{item.Habitat}}</p> 
     <p>{{item.Status}}</p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 2021-06-03
    • 1970-01-01
    • 2021-12-30
    • 2023-01-29
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多