我正在尝试在登录页面和注册页面之间共享数据。如果用户尝试登录并且身份验证失败,我希望重定向到注册页面并预先填写登录尝试数据。我正在尝试使用共享服务传递数据,在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 {
// 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 :(得分:4)
注册组件中没有数据
这是因为Subject
不会缓存任何内容。当您向其发出内容时,只有当前订阅的订阅者才会收到该消息。否则消息将永远丢失。
如果您希望缓存该值,请改用BehaviorSubject
。
另见: