【发布时间】:2020-03-14 04:30:17
【问题描述】:
在我的应用中,我的目标是从下面的这个 URL 获取数据并将其显示在我的应用中。 https://jsonplaceholder.typicode.com/posts/1
我的问题是我的应用程序中没有显示数据,控制台说我不明白在哪里更正。
firefox 控制台(ctrl+shift+k)
Angular is running in the development mode. Call enableProdMode() to enable the production mode. core.js:40471
[WDS] Live Reloading enabled. client:52
ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
Angular 21
RxJS 5
Angular 9
core.js:5882:19
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
readonly ROOT_URL = 'https://jsonplaceholder.typicode.com';
posts: any;
constructor(private http: HttpClient) {
}
getPosts() {
this.posts = this.http.get(this.ROOT_URL + '/posts/1');
}
}
**app.component.html**
<h1>Angular HTTP Basic</h1>
<button (click)="getPosts()"> get</button>
<div *ngFor = "let post of posts">
{{ post | json }}
</div>
这应该是一项简单的工作,但是 vs 代码没有给我任何错误,我不明白我的浏览器控制台的含义。请指出出了什么问题。
【问题讨论】:
-
ngFor只对数组起作用,你响应的数据是一个对象,把它改成数组,就是这个错误的意思。
标签: angular typescript httpmodule