我试图理解为什么当返回一个Observable而不是一个数组时,我得到一个对象

时间:2017-02-19 18:00:07

标签: angular observable

我正在尝试在https://coryrylan.com/blog/angular-observable-data-services之后在Angular2中构建一个可观察的数据服务。但是,我试图在我的* ngFor中迭代的变量,而不是一个数组,是一个看起来像这样的对象:

{ _isScalar: false, source: Object }

我的代码如下:

transaction.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TransactionService } from '../transaction/transaction.service';
import { Transaction } from '../transaction/transaction';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'transactions',
  templateUrl: 'app/transaction/transaction.component.html',
  providers: [TransactionService]
})

export class TransactionComponent implements OnInit {
  private transactions: Observable<Transaction[]>;
  constructor(private transactionService: TransactionService,
              private router: Router) {}

  ngOnInit(): void {
    this.transactions = this.transactionService.transactions;
    let current = new Date();
    let month: string = (current.getMonth()).toString();
    this.transactionService.retrieveTransactions(month);
  }
}

transaction.component.html:

<h2>Add a new transaction</h2>
<new-transaction></new-transaction>

<h1>My transactions</h1>
<div *ngFor="let transaction of transactions | async">
  {{transaction.name}} | ${{transaction.amount}} | {{transaction.kind}}
</div>

transaction.service.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import { Transaction } from './transaction';

@Injectable()
export class TransactionService {
  transactions: Observable<Transaction[]>;
  private _transactions: BehaviorSubject<Transaction[]>;
  private transactionUrl: string = 'http://localhost:3000/api/transactions';
  private headers = new Headers({'Content-Type': 'application/json'});
  private sessionToken: string = JSON.parse(window.localStorage.getItem('currentUser')).session_token;
  private dataStore: {
    transactions: Transaction[]
  };
  constructor(private http: Http) {
    this._transactions = <BehaviorSubject<Transaction[]>>new BehaviorSubject([]);
    this.dataStore = { transactions: [] };
    this.transactions = this._transactions.asObservable();
  }

  retrieveTransactions(month: string): void {
    let transactionUrlParams: string = this.transactionUrl;
    transactionUrlParams += `?session_token=${this.sessionToken}&month=${month}`;
    this.http.get(transactionUrlParams).map(response => response.json())
        .subscribe( data => {
          for (let t in data) {
             if (data[t]) this.dataStore.transactions = data;
          }
          this._transactions.next(Object.assign({}, this.dataStore).transactions);
        }, error => this.handleError(error));
  }

  create(kind: string, amount: number, name: string): Promise<Transaction> {
    return this.http
      .post(this.transactionUrl, JSON.stringify({
        "transaction": {
          "kind": kind, 
          "amount": amount, 
          "name": name, 
          "session_token": this.sessionToken,
          "month": new Date().getMonth()
        }
      }), {headers: this.headers})
      .toPromise()
      .then( res => {
        return res.json();
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('Error!', error);
    return Promise.reject(error.message || error);
  }
}

1 个答案:

答案 0 :(得分:0)

正如您已在服务中定义的那样,您正在查看Observableprivate transactions: Observable<Transaction[]>;)。

console.log中的Observable看起来像那样。如果您想查看它(您的数组)的内容,只需.subscribe()console.log回调中的响应。