如何将 HTTP Angular 4/5 请求绑定到 html?

How to bind an HTTP Angular 4/5 request to html?

我从 angular HTTPClient GET 请求返回了一些原始 JSON,但我不确定现在如何将我的 JSON 对象的属性绑定到我的 html动态地。

我通常会认为只是将返回的 JSON 对象存储到一个变量中,然后在我需要的地方使用点符号引用它,但是 Angular 似乎不是那样工作的我无法将我的 http get 请求设置为 ngOnInit 中的变量并引用它。

我正在使用 ngOnInit 在我的组件加载时对其进行初始化,并且它已成功登录到控制台,但是如何将它绑定到我的 html 中?

app.component.ts:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'Contacts';
  constructor (private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
    .subscribe((data) => {
      console.log(data));
  }
}

app.module.ts:

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


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


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

HTML:

<div id= contacts-container>
  <header><h1> {{ title }} </h1></header>
  <div id= "favoritesContainer">
    <p>Favorite Contacts</p>
  </div>
  <ul>
    <li *ngFor="let contact of contacts">
      <div *ngIf= "!contact.isFavorite">
          <img src={{contact.smallImageURL}} />
          <h3><img src="../assets/Favorite Star (True)/Favorite — True.png">{{ contact.name }} </h3>
          <br>
          <p>{{ contact.companyName }}</p>
          <hr>
      </div>
    </li>
  </ul>
</div>

这样试试:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'Contacts';
  constructor (private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
    .subscribe((data)=>{
         this.contacts = data;//I have assigned data here inside subscription
         console.log(data);
    });
  }
}

并以与 HTML

相同的方式引用 this.contacts

您的 app.component.ts 中似乎没有 contacts 变量。

它应该是这样的:

export class AppComponent {
  title = 'Contacts';
  contacts: any[]; // Add variable
  constructor (private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
    .subscribe((data)=>{
         console.log(data);
         this.contacts = data; // Once you get the data, assign the data returned to contacts
    });
  }
}