如何将外部api值绑定到angular接口并在组件html中显示它?

问题描述

我一直在搜索,但没有明确的答案。所以我会这样尝试。它实际上非常简单,但我只是不知道如何实现(对angular来说是新手,但了解基础知识)。

我想要一个显示资产当前价格的组件。我有这个返回JSON的api调用。 api呼叫:https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd 返回:

enter image description here

这就是问题。如何将此数据绑定到angular的接口中?我只需要在组件中显示usd价格值,但需要先将其绑定到类,以便可以在html组件中使用它。

该类需要具有哪些值?这不起作用:

enter image description here

也许有人知道一个不错的api教程,该教程显示了如何执行此操作?到目前为止,我还没有找到任何东西。我发现的那些在响应中也定义了明确的属性,例如:{ “名称”:比特币 “ usd”:10279.66 }

简而言之:从该API获取数据(仅是价格)。并在模板(angular component.html)中使用它

解决方法

要从API读取数据,您需要创建一个Angular Service

注意: Http GET返回Observable,它订阅了读取数据,并且我们必须取消订阅observable才能防止内存泄漏,有几种方法可以unsubscribe observable使用{{3 }}运营商退订。

service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

export interface IcoindDetail {
 bitcoin?: { usd: number },ethereum?: { usd: number }
}

@Injectable({providedIn: 'root'})
export class MyService {

// inject httpClient to read restful methods
constructor(private http: HttpClient) {} 

// create a method that read API URL using GET method
getData() {
  const url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd';

  // return API response
  return this.http.get<IcoindDetail>(url)
 }
}

Component.ts

data: IcoindDetail;

// inject service to read methods
constructor(private service: MyService) {}

ngOnInit() {
  // read response from API and store in data variable
  this.service.getData()
    .pipe(take(1)) // notice take(1) to unsubscribe observable  
    .subscribe((res) => this.data = res)
}

template.html

<div *ngIf="data"> {{ data.bitcoin.usd }} </div>

工作ngrx take(1)

,

您可以简单地使用service来获得API响应,然后将服务注入到所需的任何组件中(依赖注入)。使用服务的返回值设置组件的局部变量。

所以尝试这样的事情:

app.service.ts

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  const apiUrl = "https://api.coingecko.com/api/v3/simple/price? 
                        ids=bitcoin&vs_currencies=usd"

  constructor(private http: HttpClient) { }
  
  getApiRespons(): Observable()<any> {
    return this.http.get(this.apiUrl);
  }

}

app.component.ts

import { Component,OnInit } from '@angular/core';
import { ApiService } from './app.srvice';

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public obj:any = {};
  constructor(private apiService: ApiService) { }

  ngOnInit() {
   this.apiService.getApiRespons().pipe(take(1)).subscribe(
     res => {
       this.obj = res;
     }
   );
  }
}

app.component.html

<div class="container">
  <p>{{ obj.bitcoin.usd }}</p>
</div>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...