C
C
Cach2017-05-26 09:32:48
Angular
Cach, 2017-05-26 09:32:48

Passing data between components in Angular2?

Good afternoon. When the page is loaded (in app.component), the user is taken and written to the stream. account.component is connected at /account. If you open the /account page, the data from the stream is retrieved without problems. But if you first open some other page, and then go to /account, the data from the stream is not visible. Can someone suggest what is the problem? Thanks
PS @Input is not suitable for data transfer, tk. they will be accessed from top-navigation and router-outlet

<!-- app.component.html -->
<top-navigation></top-navigation>
<router-outlet></router-outlet>
<page-footer></page-footer>

//app.component

public ngOnInit(): void {
        if (localStorage.getItem(AuthTokenName)) {
            this.userService.getUser().then(
                (user) => this.userService.setUser(user),
                () => {
                    this.userService.logout();

                    this.router.navigate(['/']);
                }
            );
        }
    }

//service

private userSource = new Subject();

    public user = this.userSource.asObservable();

    public setUser(user) {
        this.userSource.next(user);
    }

//account component
public ngOnInit(): void {
        this.userService.user.subscribe((user) => this.user = user);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Manakov, 2017-05-26
@Cach

Because first you write down the user there, and then connect.
Subject passes to the subscriber only what was passed after subscribe
BehaviorSubject passes the last value passed to the subscriber + everything that arrived after subscribe
You need a BehaviorSubject

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question