2017-04-02 76 views
2

我試圖在登錄頁面和註冊頁面之間共享數據。如果用戶嘗試登錄並且身份驗證失敗,我希望通過預先填寫的登錄嘗試數據重定向到註冊頁面。我試圖通過使用共享服務的數據,聲明爲app.module.ts提供商在Angular2中路由數據之間傳遞數據

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']); 

       }); 
    } 
} 

我使用的是共享服務的數據傳遞到註冊頁面。

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(); 
    } 

} 

的數據是不可用的註冊組件

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 
      });  
    } 
+0

請你張貼每個compoennt –

回答

4

的數據是不可用的註冊組件

這是因爲Subject不緩存任何東西。當你發佈一些信息時,只有訂閱者訂閱纔會收到郵件。否則,該消息將永遠丟失。

如果要將該值緩存,請改爲使用BehaviorSubject

參見:

+0

靶心的全碼,沒有一個線索阿布德BehaviorSubject。謝謝! – Shakur

+0

一個小問題。爲什麼它需要成爲Observable?爲什麼不能像Angular 1那樣提供簡單的服務? – SRK

+0

我一直在努力,這太長,因爲我不知道主題沒有緩存。謝謝 – Anthony