【问题标题】:I am trying to understand why when returning an Observable, instead of an array, I am getting an object我试图理解为什么当返回一个 Observable 而不是一个数组时,我得到一个对象
【发布时间】:2017-02-20 03:38:47
【问题描述】:

我正在尝试在 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);
  }
}

【问题讨论】:

    标签: angular observable


    【解决方案1】:

    正如您已经在服务中定义的那样,您正在查看Observable(private transactions: Observable&lt;Transaction[]&gt;;)。

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

    【讨论】:

    • 感谢您的回复!我很困惑,因为我以为我在服务中订阅了它?我的模板出错了:Error trying to diff '[object Object]'
    • @MarkLaRosa 您正在订阅,但您没有返回订阅(无论如何您都不应该)。您正在.next()将数据发送给一个主题,该主题被分配为另一个可观察的可观察对象。所以最后你有一个可观察的:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多