Learn how to create your own Dapp with Angular 9 — Part V.
In this six-part article, we will cover how to create a Dapp with Angular. In Part I, which served as an introduction we covered general information regarding developing the dapp benefits and classification. Using Angular, Angular architecture, benefits. You should start there.
In the previous articles, we started developing our dapp. Specifically,
we learned about dapp classifications and projects and that you can
break your own dapp project into five steps.
We then looked at why to use Angular and its benefits. Next, we created an Angular project, first ensuring the prerequisites were installed and then installing the Angular CLI.
We looked at the pieces that make up Angular such as components, modules, and directives. We also learned how to style a dapp by understanding Angular-style architecture and working with Angular Material.
We started building our own custom components and creating content; we split the app into a footer, header, and body and created a custom transfer component that you will be using in this article. We created the dapp’s smart contract utilizing the following tools the Angular CLI, Truffle, ganache-cli, and MetaMask.
In this article, we will be integrating our smart contract in the dapp’s Angular
project.
In the last article, Part IV; Linking and connecting your dapp to the Ethereum
network and testing.
In the previous article, we got the contract working in Terminal; the next step is for our dapp to interact with the contract. This is done via web3.js, which is a collection of libraries allowing you to interact with a local or remote Ethereum node using an HTTP or IPC connection.
First, navigate back into your Angular project folder and then install web3.js with the flag — save to save the library you are installing.
cd ethdapp/
npm install web3 --save+ web3@1.2.4
If the installation went well, you will see in the output that the version did
install. At the time of writing, web3 is at version 1.2.4.
You also will be installing @truffle/contract, which provides wrapper
code that makes interaction with your contract easier. At the time of
writing, the latest is version 4.1.3 at the time of writing.
npm install @truffle/contract --save+ truffle-contract@4.1.3
Tip web3 version 1.2.4 and @truffle/contract version
4.0.31 are the latest versions and compatible with Angular 9.x.
However, this can change, so watch the version you are installing
to ensure it’s compatible and to avoid errors. Re-install with exact
@[version], for instance,
npm install @truffle/contract@4.1.0
In case, you run into compatibility issues.
Now that you have your libraries installed, you can continue. In this
section, you will create and write a service class. A service class is going
to be your front-end middle layer for Angular to interact with web3. To get started, you can utilize the ng s flag, which stands for “service.”
cd ~/Desktop/ethdapp
ng g s services/transferCREATE src/app/services/transfer.service.spec.ts (367 bytes)
CREATE src/app/services/transfer.service.ts (137 bytes)
Next, we need to replace the service class’s initial code with logic to interact
with web3.
To do that, first, we will define the libraries we will be using, which are the
Angular core and the truffle-contract and web3 libraries you installed.
Let’s review the code of transfer.service.ts;
import from '@angular/core';
const Web3 = require('web3');
import * as TruffleContract from 'truffle-contract';
Next, you will define three variables we will be using later: require,
window, and tokenAbi. Notice that tokenAbi points to the ABI file you
compiled from the contract SOL file in the previous article.
declare let require: any;
declare let window: any;
const tokenAbi = require('../../../truffle/build/contracts/Transfer.json');
You need access to root to interact with web3, so you need to inject it into your project.
@Injectable()
Next, define the class definition, the account and web3 variables, and
init web3.
import from '@angular/core';
const Web3 = require('web3');
import * as TruffleContract from 'truffle-contract';declare let require: any;
declare let window: any;
const tokenAbi = require('../../../truffle/build/contracts/Transfer.json');
@Injectable()
export class TransferService else
window.web3 = new Web3(this.web3);
console.log('transfer.service :: this.web3');
console.log(this.web3);
}
}
Notice that you wrapped console.log messages around the code
so you can see the messages in the browser console messages
section under developer tool mode to help you understand what’s
happening.
To do so open the browser in a developer tool mode. For Chrome, select View Developer View ➤ Developer ➤ Developer Tools.
You need an async method to get the account address and balance,
so you can use a promise function. If your account was not retrieved
previously, you’ll call web3.eth.getAccounts just as you did in Terminal to
retrieve the data. You also need error code if something goes wrong.
private async getAccount(): Promise<any> else
if (err != null)
});
}) as Promise<any>;
}
return Promise.resolve(this.account);
}
Similarly, you need a service method to interact with and get the balance
of the account. You use web3.eth.getBalance just as you did in Terminal
and wrap some error checking. You also set this as a promise. The reason
you need a promise is that these calls are async, and JavaScript is not.
public async getUserBalance(): Promise<any> ;
console.log('transfer.service :: getUserBalance :: getBalance :: retVal');
console.log(retVal);
resolve(retVal);
} else );
}
});
}) as Promise<any>;
}
Last, you need a method to pass the values from your form and transfer
payment from one account to another. Use the contract pay method and
wrap some error checking.
transferEther(value) );
}).then(function(status) );
}
}).catch(function(error) );
});
}
Now that we have the transfer service complete, we can connect
transfer.component to get the user’s account address and balance and be able to transfer funds once the form is filled in.
First, we need to define the service component we created.
src/app/component/transfer/transfer.component.ts
Open and add the import statement at the top of the document.
import from ‘../../services/transfer.service’;
For the component definition, add TransferService as a provider.
@Component()
Also, add TransferService to the constructor so you can use it in your
class.
constructor(private fb: FormBuilder,
private transferService: TransferService)
Next, update the getAccountAndBalance method to include a call to
the service class and retrieve the user actual account and balance.
getAccountAndBalance = () => ).catch(function(error) );
}
Lastly, update submitForm to call transferEther to transfer and pay.
Replace the submitForm TODO comments shown here with the call to the
service calls:
// TODO: service call
Then pass the data the user-submitted:
// TODO: service call
this.transferService.transferEther(this.userForm.value).
then(function() ).catch(function(error) );
In this article, we installed web3.js as well as truffle-contract. We then created our transfer service in Angular and connected our component class to the service class.
Continue following our articles as in the next and last article we will be covering;
- Part VI — Linking and connecting our dapp to the Ethereum network
To learn more about what’s possible with Blockchain as well as develop your own project check The Blockchain Developer.
You can follow me on Medium for more posts like this and find me on Twitter as well. Are you starting your own Blockchain project, need a startup advisor? Reach out to me on Linkedin.
Published at Sun, 05 Jan 2020 15:01:30 +0000
{flickr|100|campaign}
