1
我想在後在Angular2中構建一個可觀察數據服務。但是,我想在我的* ngFor遍歷變量,而不是一個數組,是一個對象,看起來像這樣:我想理解爲什麼當返回一個Observable而不是一個數組時,我得到一個對象
{ _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);
}
}
感謝您的回覆!我很困惑,因爲我認爲我在服務中訂閱了它?我的模板出錯了:錯誤試圖區別'[object Object]' –
@MarkLaRosa你訂閱,但你沒有返回訂閱(你不應該)。您將'.next()'數據轉換爲被指定爲另一個可觀察對象的可觀察對象。所以最後你有一個可觀察的:-) – echonax