【问题标题】:Angular : can't get data from url using HttpClientModuleAngular:无法使用 HttpClientModule 从 url 获取数据
【发布时间】: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


【解决方案1】:

你需要订阅你的 observable:

  posts: any[] = [];

  getPosts() {
     this.http.get(this.ROOT_URL + '/posts/1').subscribe((post) => {
       this.posts = [post];
     });
  }

或者你可以结合使用 observables 和 angular 的力量:

  import { map } from 'rxjs/operators';
  import { Observable } from 'rxjs';

  posts: Observable<any[]>;

  getPosts() {
     this.posts = this.http.get(this.ROOT_URL + '/posts/1').pipe(
       map((post) => [post])
     );
  }
<div *ngFor = "let post of posts | async">
  {{ post | json }}
</div>

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 2018-10-03
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多