我試圖在登錄頁面和註冊頁面之間共享數據。如果用戶嘗試登錄並且身份驗證失敗,我希望通過預先填寫的登錄嘗試數據重定向到註冊頁面。我試圖通過使用共享服務的數據,聲明爲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
});
}
請你張貼每個compoennt –