Quickstart Angular
Introductionβ
This tutorial shows you how to create a basic Angular dapp and use the Moralis SDK to display on-chain balances. You'll create a balances page and an Express.js API endpoint returning native and ERC20 balances for an address.
The Steps We Will Takeβ
- Create an Angular dapp
- Set up the Moralis SDK on the server
- Integrate your app with Moralis
- Read any blockchain data from any blockchain
Prerequisitesβ
- Follow the Your First Dapp for Node.js tutorial
Create an Angular Dappβ
We will follow the instructions here for setting up an Angular project.
- Install the Angular CLI:
npm install -g @angular/cli
- Create a new folder for your project and open it in your editor. Create a new Angular project - select
yes
for routing and choose any stylesheet format:
ng new your-first-dapp-angular
- Install the required dependency:
axios
- to make requests to our server (You can also use Angular's HTTP module
- npm
- Yarn
- pnpm
npm install axios
yarn add axios
pnpm add axios
- Open
src/app/app.component.html
and get rid of the boilerplate HTML and CSS code. Remove everything except for:
<router-outlet></router-outlet>
- We will generate a component or page called
/balances
for displaying the balances:
ng generate component balances
- Open
src/app/app.routes.ts
and add this component as a route:
import { BalancesComponent } from "./balances/balances.component";
const routes: Routes = [{ path: "balances", component: BalancesComponent }];
- Open
src/app/balances/balances.component.html
and replace the contents with:
<div>
<h3>Wallet: {{ address }}</h3>
<h3>Native Balance: {{ nativeBalance }} ETH</h3>
<h3>Token Balances: {{ tokenBalances }}</h3>
</div>
- Open
src/app/balances/balances.component.ts
and add these three variables we defined above:
export class BalancesComponent implements OnInit {
constructor() {}
address = "";
nativeBalance = "";
tokenBalances = "";
ngOnInit(): void {}
}
- Run the command
npm run start
and open http://localhost:4200/balances in your browser. It should look like:
We have not fetched any data yet - we will update our server code and then we will get this data from our Angular dapp.
Set up the Serverβ
Follow this tutorial for setting up your server. We will need a server to use the Moralis API without needing to expose our API key on the client side.
- Replace the contents of
index.js
with the following (make sure to add your own API key):
const Moralis = require("moralis").default;
const express = require("express");
const cors = require("cors");
const { EvmChain } = require("@moralisweb3/common-evm-utils");
const app = express();
const port = 3000;
// allow access to Angular app domain
app.use(
cors({
origin: "http://localhost:4200",
credentials: true,
})
);
const MORALIS_API_KEY = "replace_me";
const address = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d";
app.get("/balances", async (req, res) => {
try {
// Promise.all() for receiving data async from two endpoints
const [nativeBalance, tokenBalances] = await Promise.all([
Moralis.EvmApi.balance.getNativeBalance({
chain: EvmChain.ETHEREUM,
address,
}),
Moralis.EvmApi.token.getWalletTokenBalances({
chain: EvmChain.ETHEREUM,
address,
}),
]);
res.status(200).json({
// formatting the output
address,
nativeBalance: nativeBalance.result.balance.ether,
tokenBalances: tokenBalances.result.map((token) => token.display()),
});
} catch (error) {
// Handle errors
console.error(error);
res.status(500);
res.json({ error: error.message });
}
});
const startServer = async () => {
await Moralis.start({
apiKey: MORALIS_API_KEY,
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
};
startServer();
- Run this command to start the server:
npm run start
- Open
http://localhost:3000/balances
in your browser. The output should be similar to the following:
{
"address": "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",
"nativeBalance": "0.010201",
"tokenBalances": ["101715701.444169451516503179 APE", "0.085 WETH"]
}
Bringing It All Togetherβ
Now that we have our server set up to get the native balance and ERC20 token balances for an address, we will make a request to http://localhost:3000/balances
from our Angular app so we can display it on a page.
- Open
src/app/balances/balances.component.ts
and importaxios
at the top to make HTTP requests:
import axios from "axios";
- Replace
ngOnInit(): void {}
with:
async ngOnInit() {
const { data } = await axios(`http://localhost:3000/balances`);
this.address = data.address;
this.nativeBalance = data.nativeBalance;
this.tokenBalances = data.tokenBalances;
}
This will fetch the balances data from our server when the page is loaded and set the component variables which will be displayed. The final balances.component.ts
should look like:
import { Component, OnInit } from "@angular/core";
import axios from "axios";
@Component({
selector: "app-balances",
templateUrl: "./balances.component.html",
styleUrls: ["./balances.component.css"],
})
export class BalancesComponent implements OnInit {
constructor() {}
address = "";
nativeBalance = "";
tokenBalances = "";
async ngOnInit() {
const { data } = await axios(`http://localhost:3000/balances`);
this.address = data.address;
this.nativeBalance = data.nativeBalance;
this.tokenBalances = data.tokenBalances;
}
}
- Reload the
http://localhost:4200/balances
page to see the results: