L
L
link_irk2017-01-26 06:45:25
JavaScript
link_irk, 2017-01-26 06:45:25

How to get data from service in child component after change by parent?

Hello.
I apologize for the somewhat confused description and terminology, until I fully understand the specifics of development on Angular 2.
I have the following component hierarchy:
MemberComponent -> DesktopComponent (router-outlet) -> PaymentHistoryComponent
Service: AccountService.

export class AccountService {
    public accountSource = new Subject();
    public account: Observable<any> = this.accountSource.asObservable();

    public getAccount() {
        return this.account;
    }

    public setAccount(account) {
        this.accountSource.next(account);
    }
...

The MemberComponent has a drop-down-list with a list of personal accounts, which, when changed, calls the method
public changeAccount() {
    this.accountService.setAccount(this.account);
}

PaymentHistoryComponent:
export class PaymentHistoryComponent implements OnInit {
    public history;

    public constructor(
        public paymentService: PaymentSercice,
        public accountService: AccountService,
        public router: Router
    ) {

    }
    
    public ngOnInit() {
        this.accountService.getAccount().subscribe((account) => {
            this.paymentService.getHistory(account.value).then(history => this.history = history);
        });
    }
}

When the application loads, the MemberComponent selects the first account from the list and calls the changeAccount method. Thus, the AccountService::setAccount method is called.
At the next stage of the application loading, the PaymentHistoryComponent is connected and subscribes to the Observable from the AccountService service, the value of which has already been set earlier. So no callback is called
this.accountService.getAccount().subscribe(...)

But if you now choose some other face from the list, then the script works out correctly.
How to get the value already available in AccountService.account when initializing the PaymentHistoryComponent component

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2017-01-26
@link_irk

And this is a question for RxJS, not Angular. The easiest way to solve your question is to replace Subject with BehaviourSubject. It will need an initial value during construction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question