以下是组件:
import { Component, OnInit } from '@angular/core';
import { imageApi } from 'app/apis';
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import store_artifacts from 'build/contracts/Store.json'
import { LogService } from 'app/services';
@Component({
selector: 'bcs-app',
templateUrl: './bcs.component.html',
styleUrls: [
'./bcs.component.scss'
]
})
export class BcsComponent implements OnInit {
public accounts: any[] = [];
public account: any;
private _web3: any;
public Store: any;
constructor(private logger: LogService) { }
public ngOnInit() {
console.log('BCS component loaded');//prints as expected
this.initWeb3();
this.Store = contract(store_artifacts);
this.Store.setProvider((window as any).web3.currentProvider);
this._web3 = (window as any).web3;
this._web3.eth.getAccounts((err, accs) => {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
this.account = "Couldn't get any accounts"
} else{
this.accounts = accs;
this.account = (accs.length == 1)?this.accounts : this.accounts[0];
}
console.log(this.account);//<= Here value exists
});
}
public initWeb3() {
// some code
}
}
模板是这样的:
<div class="well">
Your account: {{account}}
</div>
在UI上无需渲染