Tutorial: Building enterprise applications with Angular 6, NgRx and RxJs - Lesson 2

in #utopian-io6 years ago

NgRx Store: https://github.com/ngrx/store
Angular 6: https://github.com/angular/angular
Steem API Docs: https://developers.steem.io/

Github repository: https://github.com/mightypanda-x/ngrx-tut

This tutorial is a tangent from the last one where we were using git api to get data. In this tutorial we will learn how to get data using steem api and angular 6 because this information is not documented on the internet.

What will you learn in this tutorial?

  • Installing steem api and a workaround for "fs module not found in zone.js" error
  • Get accounts using steem condenser API async function
  • Reading data from the state and display on the front end.

Requirements

Difficulty: Intermediate


Clone and run git project

Clone the git project so you can follow along with the steps and run the application

$ git clone [email protected]:mightypanda-x/ngrx-tut.git
$ cd ngrx-tut
$ npm install

Installing Steem API

Steem has a node module that you can easily install and save in package.json file by running following command

npm install steem --save

Adding patch.js file and npm postscript for "fs module issue"

Angular currently throws a fs module not found in zone.js error when using steem. To fix this, add patch.js file on the same level as package.json

patch.js

const fs = require('fs');
const f = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';

fs.readFile(f, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/node: false/g, 'node: {crypto: true, stream: true, fs: \'empty\', net: \'empty\'}');

  fs.writeFile(f, result, 'utf8', function (err) {
    if (err) return console.log(err);
  });
});

Also add an entry withing scripts block in package.json file to run this file as post install task:

"postinstall": "node patch.js"

** Now run npm install to run this post script.**

Profile Service

profile.service.ts

public retrieveSteemProfile(username: string, cb): Promise<any> {
    return steem.api.getAccountsAsync([username], cb);
  }

getAccountsAsync is the asynchronous method to get the account information. First argument of the method is the list of usernames you want to get information for. Second argument is a callback method which will process the response once returned.

Profile Effect

profile.effects.ts

@Effect()
  getUserProfile = this.actions.pipe(
    ofType(ProfileActionTypes.RetrieveUserProfile),
    switchMap((action: RetriveUserProfile) => this.profileService.retrieveSteemProfile(action.payload, (err, userProfile) => {
      if (err) {
        catchError(error => this.profileService.handleAuthError(error));
      }
      this.store.dispatch(new RetrieveUserProfileSuccess(userProfile[0]));
    }))
  );

Profile Effect intercepts the call to action and called service. It passed the action payload which is the username and a callback method which will be used to process the response from the service. In this case, it will call RetrieveUserProfileSuccess action with userProfile data object. In case of error, it will call the Error function.

Profile Reducer

profile.reducers.ts

    case ProfileActionTypes.RetrieveUserProfileSuccess: {
      return action.payload;
    }

Profile reducer creates a new state with the data retrieved from the steem apis.

User Profile Component

user-profile.component.ts

    this.profileData$ = store.select('user');
    this.profileData$.subscribe((user) => {
      const profileMetadata = _.get(user, 'profile.json_metadata');
      if (profileMetadata) {
        const jsonMetadata = JSON.parse(profileMetadata);
        this.profileData = jsonMetadata.profile;
      }
    });

As described in the previous tutorial, component is where we subscribe to the changes in store. In this case, we are subscribing to the user store. When this store gets new data, we extract json_metadata from the profile which contains profile image and description.

user-profile.component.html

<div class="card" style="width: 18rem;" *ngIf="profileData">
  <img class="card-img-top" src="{{profileData.profile_image}}" alt="Card image cap">
  <hr>
  <div class="card-body">
    <h5 class="card-title">{{profileData.name}}</h5>
    <p class="card-text">{{profileData.about}}</p>
  </div>
</div>

Here we are using the profileData object to display image and name data on the html page.
image.png

Running the application

Go the terminal and type

$ ng serve

This will compile and run the application on http://localhost:4200. Type in any steem username and it will show the profile.

Summary

Lesson 1 was focused on strengthening the basics of NgRx and Angular 6. In this tutorial you learned to interact with steem blockchain using Steem Condenser API. Condenser APIs are a powerful tool to interact with steem blockchain and have method which can be used to do variety of operations like getting account history, post information, account status etc.

GitHub for the tutorial:

https://github.com/mightypanda-x/ngrx-tut

Sort:  

Thank you for your contribution.

  • Your tutorial is simple and easy to understand ;)

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thanks for the review. I was aiming for simple.

Hey @mightypanda
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 69831.92
ETH 3744.43
USDT 1.00
SBD 3.77