从角度2.rc4到最终

时间:2016-10-16 23:20:57

标签: angular rxjs observable

由于我的应用程序从角度2.rc.4和rxjs.beta.6升级到角度2 final和rxjs.beta.12以下,因此不再适用。我没有收到错误消息,我在更改日志中找不到任何内容。我在有问题的代码中插入了一些注释。所有这些在rc.4中都运行良好。

服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { ApiService } from './api.service';

@Injectable()
export class StocksService {

  private _portfolio: BehaviorSubject<any>;
  private _transactions: BehaviorSubject<any>;

  constructor(private apiService: ApiService) { 
    this._portfolio = BehaviorSubject.create();
  }

  get portfolio() {
    return this._portfolio.asObservable();
  }

  get transactions() {
    return this._transactions.asObservable();
  }

  loadPortfolio(): void {
    this.apiService.get('/depot')
    .map(res => res.json())
// the correct data is in res.data here, but it doesn't get to the component
    .subscribe(res => this._portfolio.next(res.data));
  }

  loadTransactions(): void {
    this.apiService.get('/transactions')
    .map(res => res.json())
    .subscribe(res => this._transactions.next(res.data));
  }

  search(id: string) {
    return this.apiService.get('/stocks/search')
    .map(res => res.json());
  }

}

和组件

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { StocksService } from './stocks.service';

@Component({
  selector: 'tradity-portfolio',
  templateUrl: 'app/portfolio.component.html',
  providers: [StocksService]
})
export class PortfolioComponent implements OnInit {

  portfolio: Observable<any>;

  constructor(private stocksService: StocksService) { }

  ngOnInit() {
    this.portfolio = this.stocksService.portfolio;
// the following console.log doesn't fire like it used to in rc.4
    this.portfolio.subscribe(val => console.log("received", val));
    this.stocksService.loadPortfolio();
  }

}

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。错误在于服务的构造函数。

constructor(private apiService: ApiService) { 
    this._portfolio = BehaviorSubject.create();
}

应该是

constructor(private apiService: ApiService) { 
    this._portfolio = new BehaviorSubject("");
}