Simple http get api json / render data in template


#1

This is probably so basic I’m embarrassed to post, but oh well…

I am learning how to pull json data from an api, display part of it and use it to perform a calculation. Many tutorials are outdated and I know I’m missing something critical. I don’t need to loop through any data, just fetch, access and display.

Here’s the api json:

https://api.cryptonator.com/api/ticker/btc-usd

I’ve created a provider:

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


@Injectable()
export class CryptoProvider {

  private cryptoURL = 'https://api.cryptonator.com/api/ticker/btc-usd';

  constructor(private http: HttpClient) {

  }

  fetchBTC(): Observable<any> {
    return this.http.get(this.cryptoURL);
  }  
 
}

I want to use the fetched data on this page:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ListMasterPage } from '../list-master/list-master';
import { TranslateService } from '@ngx-translate/core';
import { CryptoProvider } from '../../providers/crypto/crypto';

@IonicPage()
@Component({
  selector: 'page-transact',
  templateUrl: 'transact.html',
  providers: [CryptoProvider]
})
export class TransactPage {

  subtotal: number = 0;

  bitcoin: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private cryptoProvider: CryptoProvider) {
    
  }

  ionViewDidLoad() {
    this.subtotal = this.navParams.get('usd');
    this.fetchBTC();
  }
 
 
  fetchBTC(): void {
    this.bitcoin = this.cryptoProvider.fetchBTC()  
  }

}

Any pointers would be great! Thanks in advance.


#2

Hello,
I am not sure if I understood you correct. Maybe you looking something like that: https://angular.io/guide/template-syntax.

Or did you mean using this.bitcoin on .ts side?

Best regards, anna-liebt


#3

Or did you mean using this.bitcoin on .ts side?

Yes. I’m not sure how to access the json data and use it to render in the template.

I would like to access the “price” data in the json and display it in the html.

{
"ticker":{
"base":"BTC",
"target":"USD",
"price":"8016.22283686"
,"volume":"70342.62085660",
"change":"-14.18425355"},
"timestamp":1523735581,
"success":true,"error":""
}

Thank you.


#4

The long answer to your question is to read this. if you take the time now to build a foundation, you will avoid lots of time sink errors.


#5

Hello,

maybe this helps https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

and showing in *.html see above.

Best regards, anna-liebt


#6

U need to subscribe to the observable otherwise nothing will happen

Also read angular.io on http client

Actually: read through the whole tutorial on angular.io to set that foundation

Some basic stuff you r missing indeed but quite essential to get u to the next level

Check the readings as posted by all


#7

I’ve been reading through the info posted by all and trying the ideas. I appreciate the effort to provide learning resources!

Thank you for the advice to subscribe. I’ll look at how to implement it.

Best,
Adam


#8

Try this and build from there

  ionViewDidLoad() {
    this.subtotal = this.navParams.get('usd');
    this.fetchBTC().subscribe(data=>{ console.log('data received',data)})
  }

#9

Someone has done the heavy lifting for you


#10

I was just going through that tutorial, thanks. :+1:

Also, the console.log you suggested did show that data was being received from the api.


#11

Here’s an example of something I’m working on with Facebook api.
Service.ts

//////////////////////////////////////////////////////////
getFeed() {
  return Observable.create(observer => {
    if(this.fbSession.status === 'connected'){
      this.fb.api('/me/feed/?fields=name,story,message,caption,full_picture,link,picture',
      ['user_likes','user_photos','user_posts']).then((res)=>{
        console.log(res);
        observer.next(res);    //We return the Facebook response with the fields name and picture
        this.feed = res.data;        
        observer.complete();
        localStorage.setItem(res.data, "fbUserFeed");                          
      },(error) => {
        console.log(error) });
    } else {
      observer.next(undefined);
      observer.complete();
    }
  });
 }
 //////////////////////////////////////

Feed.ts

LoadFacebookFeed() {
      if(this.FacebookService.fbSession.status == "connected"){  
        this.FacebookService.getFeed().subscribe((feed)=>{
            this.userFeed = feed;
            this.updateFeedInfo(feed.data);
            console.log("I tried to update the feed info and render")
          }, (error)=>{console.log(error);});
      }
    }    




 updateFeedInfo(posts_in_feed) {
    // push into cards 
    for(var i=0; i<posts_in_feed.length; ++i){
      this.cards.push({avatarImageUrl: '', 
        name: JSON.parse(JSON.stringify(posts_in_feed[i])).name,
        postImageUrl: JSON.parse(JSON.stringify(posts_in_feed[i])).full_picture, 
        postText: JSON.parse(JSON.stringify(posts_in_feed[i])).message, 
        story: JSON.parse(JSON.stringify(posts_in_feed[i])).story,
      });
    }
 }

// The below code is not necessary 
feed = [
    {
      postImageUrl: 'data.url.full_picture',
      text: this.feed.message,
      date: this.feed.date,
      likes: this.feed.likes,
      comments: this.feed.comments
      timestamp: this.feed.data,
    },
  ];

IIn your case you’d probably do something like this to update the Bitcoin price.

refreshMedias() {
  console.log("I'm being called.")
  // start off with 2 minutes
  const mediaUpdateTimeframe = 15000;

  setInterval(function() {
// Make a call to Facebook api
    this.fb.api('/me/feed/?fields=story,message,caption,full_picture,link,picture',
      ['user_likes','user_photos','user_posts']).then((res) => {
      this._data = res.data;
      this.storage.setItem("facebook_info", this._data).then(done => {
        this.updateFeedInfo();
      })
      }, (error) => {
        console.log(error)
      })
  }.bind(this), mediaUpdateTimeframe);
 }

#12

You can simply run the AVD (Android virtual device) from within the Android studio. Drag your apk file to the the running virtual Android device. Then go to your chrome browser navigate to the link chrome://inspect now when you run your application on the virtual Android chrome inspect will detect the app running. Within your inspect window you can select the console tab to debug. This will also show the API call and the json response. If you’re and Android person you can do this with Android phone connected to your PC


#13

Now, if you want to code like a boss, then you use RXjs’ operator interval to create the poller, instead of this pattern

And as the facebook api returns a promise, you are easier of using the of (or from, I forgot) operator to transform it into observable instead of new