angularjs2:http-post后更新数组

时间:2016-03-29 10:22:21

标签: angularjs angular

我想知道正确的方法,如何在http post后更新数据数组。

我所拥有的是使用这些方法的交易服务:

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());
      }
      );

和一个组件

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">
---

首先,通过导航到“/ home”,我正在加载一组用户事务。

单击按钮,将调用makeTransaction()方法。它由服务TransactionService -> createTransaction执行http post请求。我认为在事务成功完成后我会重定向到“/ home”,但是这不起作用..(我假设构造函数不会再被调用。)可能是我可以以某种方式从服务更新public transactions: Transaction[]; ?也许参考?

1 个答案:

答案 0 :(得分:1)

如果要在所有交易列表中查看新交易。您可以利用包含列表和可观察对象的共享服务,以便在新事务完成时通知。

事实上,组件中的transactions列表未链接到“创建事务”调用。

以下是一个示例实现:

export class TransactionService {
  private transactionObservable:Observable<any>;
  private transactionObserver:Observer<any>;

  constructor() {
    this.transactionObservable((observer:Observer) => {
      this.transactionObserver = observer;
    }).share();
  }

  notifyTransactionCreated(transaction:any) {
    this.transactionObserver.next(transaction);
  }

  onTransactionCreated(callback:(transaction:any) => void) {
    this.transactionObservable.subscribe(callback);
  }

  (...)

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.notifyTransactionCreated(response.json()); // <------
        this.router.parent.navigateByUrl(redirect);
      },
      error => {
        alert(error.text());
        console.log(error.text());
      }
     );
   }
}

通过这种方式,您可以在组件中得到通知并更新交易列表:

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;
    });

    this.trnService.onTransactionCreated(transaction => {
      this.transactions.push(transaction);
    });

    return;
  }

  makeTransaction(){
    var userid = this.loginService.getUserId();
    this.trnService.createTransaction(10, 2, userid, 1, "/home");
  }
}

要为整个应用程序共享一个服务实例,请不要忘记在引导应用程序时指定服务:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  TransactionService
]);