API(get) response(JSON) 不在 ngFor 中显示 - Angular

API(get) response(JSON) not display in ngFor - Angular

我试图在 API 的 JSON 中获得响应,并在 Angular 中显示值 页面,使用 ngFor

我没有任何构建错误,值根本不显示在页面上,仅在控制台中使用 console.log(),所以我看不懂。

这是我的component.ts:

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

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

export class VpsComponent implements OnInit {
  vpsOptions: any;
  baseUrl: string = "http://127.0.0.1:8000/"
  valor: number = 555;
  tipo: any = "mês";

ngOnInit(): void {
   this.getVps()
   console.log("ngOnInit")
   console.log(this.vpsOptions)
}

constructor(private httpClient: HttpClient) {
    this.vpsOptions = []
}
public getVps() {
 this.httpClient.get(this.baseUrl+'vps').subscribe((result:any) =>{
  for(let item in result){
   this.vpsOptions.push(result[item]);
  }
});

这是我的component.html:

<ng-container *ngFor="let vps of vpsOptions">
      <div class="swiper-slide">
        <div class="mini-card">
          <div class="card-header img-fluid border-0">
            <h3 class="card-title titulo-mini-card">{{vps.nome}}</h3>
          </div>
          <div class="card mb-xl-8">
            <div class="card-body body-vps pt-0">
              <p class="texto-vps">
                <span class="primeira-linha"> R$ <span class="valor-vps">{{valor}},00</span>/{{tipo}}</span> <br>
                <span class="descritivo-valor">**Preço na contratação de 48 meses </span><br>
                {{vps.processador}} <br>
                {{vps.memoria}} <br>
                {{vps.disco1}} de Armazenamento <br>
                {{vps.banda}} de Banda <br>
                {{vps.ips}} IP(s) dedicado(s) <br>
                100% Acesso Root <br>
                100Mb/s Rede <br>
                Suporte 8/5 <br> <br>
                <button type="submit" class="btn btn-primary" style="background-color: #213B89;"
                >Solicitar Orçamento</button>
                <!-- <a class="link-vps" href="">Veja todas as caracterísicas</a> -->
              </p>
            </div>
          </div>
        </div>
      </div>
</ng-container>

这是我的回复API(我使用的是Python的快速API):

这是浏览器控制台的响应:

您的 vpsOptions 应该是可观察的

在你的 ts 中你应该做的:

vpsOptions$: new Observable<any>;

 ...

ngOnInit(): void {
   this.vpsOptions$ = this.getVps()
   ...
}

或更简洁的方式:

vpsOptions$ = this.getVps();

...

然后在您的模板中您可以执行以下操作:

<ng-container *ngFor="let vps of (vpsOptions$ | async)">
    ...your content
</ng-container>

这是。

祝你好运angular!

我重构了我的代码并创建了其他 类 来抽象一些功能,以进行更多练习。

我创建了一个 interface.ts 来格式化我的 get:

export interface Vps{
  id?: number;
  nome?:string;
  ...

我创建了一个 service.ts 来抽象 httpClient.get() 函数:

import { Vps } from './vps.interface';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })

export class VpsService {
  private readonly baseUrl: string = "http://127.0.0.1:8000/"
  constructor(private httpClient: HttpClient) {}

  getVps(): Observable<Vps[]> {
    const url = this.baseUrl+'vps';
    return this.httpClient.get<Vps[]>(url);
  }
}

感谢@Dario 的回答,我使用了 Observable: //声明对象

vpsOptions: Observable<Vps[]>;

//初始化对象调用service.ts

constructor(private vpsService: VpsService) {
    this.vpsOptions = this.vpsService.getVps();
  }

//最后,我更改了component.html以正确接收对象(Observable)

<ng-container *ngIf="vpsOptions | async as options">
    <ng-container *ngFor="let option of options">
         <!-- my display logic here -->
     </ng-container>
</ng-container>