在Angular2中在路由之间传递数据

11 浏览
0 Comments

在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"); // 在这里无法获取到数据
            });    
    }
}

0
0 Comments

问题出现的原因是因为Subject不会缓存任何数据。当你向它发出消息时,只有当前订阅的观察者才会收到消息。否则消息将永远丢失。

如果你想要缓存值,可以使用BehaviorSubject

解决方法是使用BehaviorSubject来替代Subject,因为BehaviorSubject会缓存最新的值。

在Angular 2中,为什么需要使用Observable而不是简单的服务,类似于Angular 1的情况,这是一个小问题。

我已经为此苦苦挣扎了很长时间,因为我不知道Subject不会缓存。非常感谢!

0