Pass data between routes in Angular2

I’m trying to share data between the login page and the sign-up page. If the user tries to login and authentication fails I wish to redirect to the sign-up page with the login attempt data pre-filled. I’m trying to pass the data using a shared service, declared as provider in app.module.ts

import {Component, Input, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {AuthenticationService} from "../../services/authentication.service";
import {SharedService} from "../../services/shared.service";

@Component({
    selector: 'my-page-login',
    templateUrl: 'login.component.html',
    styleUrls: ['login.component.scss']
})

export class PageLoginComponent implements OnInit {

    constructor( 
                 private router: Router,
                 private authenticationService: AuthenticationService,
                 private sharedService: SharedService
    ) {}


    onSubmit(data) {

        this.sharedService.setData(data);
        this.authenticationService.login(data)
            .subscribe(
                data => {
                },
                error => {

                    this.router.navigate(['/sign-up']);

                });
    }
}

I’m using a shared service for passing the data to the sign-up page.

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import {Observable} from "rxjs/Observable";

@Injectable()
export class SharedService {
    // Observable string sources
    private subject = new Subject<string>();


    setData(data) {
        this.subject.next(data);
    }
    getData(): Observable<any> {
        return this.subject.asObservable();
    }

}

Data are not available in sign-up component

import { Component } from '@angular/core';
import {Router} from "@angular/router";
import {SharedService} from "../../services/shared.service";
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'my-page-sign-up',
    styles: [],
    templateUrl: './sign-up.component.html'
})

export class PageSignUpComponent {
    private subscription: Subscription;
    constructor(
        private router: Router,
        private sharedService: SharedService
    ) {

    }


    ngOnInit() {

        this.subscription = this.sharedService.getData().subscribe(
            data => {

                console.log(data, "Data"); //not getting here
            });    
    }

Answer

Data are not available in sign-up component

It’s because Subject does not cache anything. When you emit something to it, only subscribers that are currently subscribed will get the message. Otherwise the message is lost forever.

If you want the value to be cached, use a BehaviorSubject instead.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *