在Angular2中在路由之间传递数据
在Angular2中在路由之间传递数据
我正在尝试在登录页面和注册页面之间共享数据。如果用户尝试登录但身份验证失败,我希望重定向到注册页面,并预填充登录尝试的数据。我尝试使用一个在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']); }); } }
共享服务的代码如下:
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from "rxjs/Observable"; @Injectable() export class SharedService { private subject = new Subject(); setData(data) { this.subject.next(data); } getData(): Observable { 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"); // 在这里无法获取到数据 }); } }