试图在Angular 5中访问变量外部构造函数范围

时间:2018-03-06 16:26:09

标签: angular typescript angular5

这是Angular项目中我的服务层的一部分。为什么console.log未定义count?我只能访问订户功能中的值。我想在BehaviorSubject中使用count;我怎么能在那里访问它?

export class DataService {

    public count;
    private baskets;

    constructor(private _store: StoreService) {
            this._store.reviewBasketProduct().subscribe(data => {
            this.baskets = data;
            //console.log(data.len)
            this.count =  this.baskets.length;
        })

        console.log('aa' + this.count)
    }

    private messageSource = new BehaviorSubject<number>(this.count);
    currentMessage = this.messageSource.asObservable();
}

1 个答案:

答案 0 :(得分:2)

您需要在订阅中编写控制台,因为控制台在reviewBasketProduct订阅之前执行。

import { OnInit } from '@angular/core';

export class DataService implements OnInit {

    public count;
    private baskets;
    private messageSource;

    constructor(private _store: StoreService) {
        this._store.reviewBasketProduct().subscribe(data => {
            this.baskets = data;
            //console.log(data.len)
            this.count = this.baskets.length;
            console.log('aa' + this.count);
        });
    };

    ngOnInit() {
        this.messageSource = new BehaviorSubject < number > (this.count);
        currentMessage = this.messageSource.asObservable();
    }
}