[英]How to bind external api values to an angular interface and show it in a component (html)?
我一直在尋找和尋找,但沒有明確的答案。 所以我會以這種方式嘗試。 它實際上非常簡單,但我只是不知道如何實現它(Angular 新手,但了解基礎知識)。
我想要一個顯示資產當前價格的組件。 我有這個返回 JSON 的 api 調用。 api調用: https ://api.coingecko.com/api/v3/simple/price?ids = bitcoin & vs_currencies = usd 返回:
但事情是這樣的。 如何將此數據綁定到 angular 接口? 我只需要在組件中顯示美元價格值,但需要先將其綁定到一個類,以便我可以在 html 組件中使用它。
也許有人知道一個很好的 api 教程來展示如何做到這一點? 我還沒有找到任何。 此外,我發現在響應中定義了明確的屬性,例如:{“名稱”:比特幣“usd”:10279.66}
簡而言之:從該 API 獲取數據(只是價格)。 並在模板中使用它(angular component.html)
要從 API 讀取數據,您需要創建一個 Angular Service
注意: Http GET 返回我們訂閱讀取數據的 Observable,我們必須要取消訂閱 observable 以防止內存泄漏,有幾種方法可以取消訂閱 observable我使用ngrx take(1)操作符取消訂閱。
服務.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)
}
}
組件.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)
}
模板.html
<div *ngIf="data"> {{ data.bitcoin.usd }} </div>
工作演示
您可以簡單地使用service
來獲取API
響應,然后將您的服務注入到您想要的任何組件中(依賴注入)。 使用服務的返回值設置組件的局部變量。
所以嘗試這樣的事情:
應用服務.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;
}
);
}
}
應用程序組件.html
<div class="container">
<p>{{ obj.bitcoin.usd }}</p>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.