I'd like to know the correct approach, how to update data-array after http post.
What I have is a transaction service with those methods:
getUserTransactions(user_id) {
return this.http.get('http://localhost:3000/users/' + user_id + '/transactions', { headers: contentHeaders })
.map(res => res.json());
}
createTransaction(balance, amount, user_id, paymethod_id, redirect) {
let body = JSON.stringify({ balance, amount, user_id, paymethod_id });
this.http.post('http://localhost:3000/transactions', body, { headers: contentHeaders })
.subscribe(
response => {
this.router.parent.navigateByUrl(redirect);
},
error => {
alert(error.text());
console.log(error.text());
}
);
and a component
export class HomeComponent {
public transactions: Transaction[];
constructor(
private router: Router,
private loginService: LoginService,
private trnService: TransactionService
) {
if (!loginService.isLoggedIn())
this.router.parent.navigateByUrl('/logout');
var userid = this.loginService.getUserId();
this.trnService.getUserTransactions(userid).subscribe(transactions => this.transactions = transactions);
return;
}
makeTransaction(){
var userid = this.loginService.getUserId();
this.trnService.createTransaction(10, 2, userid, 1, "/home");
}
}
html:
<tbody>
<tr *ngFor="#transaction of transactions; #index=index">
---
So first, by navigating to "/home" I am loading an array of user transactions.
by clicking a button, the makeTransaction()
method is called. which executes a http post request by the service TransactionService -> createTransaction
. I thought I would redirect to "/home" after transaction is successfully done, but this does not work.. ( I assume that the constructor is not called again.) may be I could update the public transactions: Transaction[];
from the service somehow? Maybe making a reference?