Ng2通过服务在组件之间共享数据
问题描述:
在遵循每个步骤之后,我仍然面临同样的问题。Ng2通过服务在组件之间共享数据
仍然不能够通过共享服务组件之间共享数据。
我的工作流程:通过登录服务登录后,我想分享关于页面的UserDetails响应。
我只注射登录服务app.module.ts在@NgModule作为供应商
===登录组件=====
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { UserAccount } from '../model/userAccount.interface';
import { LoginService } from './login.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
})
export class LoginComponent {
emailAddress : string;
password : string;
submitted : boolean;
errorMessage : string;
constructor(private loginService: LoginService, private router : Router) {
this.submitted = false;
}
login() {
// event.preventDefault();
this.submitted = true;
this.loginService.getLogin(this.emailAddress, this.password).subscribe(
u => this.router.navigate(['/about']),
error => this.errorMessage = <any>error);
}
}
== =登录服务====
@Injectable()
export class LoginService {
private userAccount : UserAccount[];
constructor (private http: Http) {}
getLogin(): Observable<UserAccount[]> {
return this.http.get(this.url)
.map(this.extractData);
}
private extractData(res: Response) {
let body = res.json();
this.userAccount = body.data.user[0]
return this.userAccount || { };
}
getUserDetails() {
return this.userAccount;
}
}
======关于组件=====
export class AboutComponent implements OnInit{
// initialize a private variable _data, it's a BehaviorSubject
// private _data = new BehaviorSubject<UserAccount[]>([]);
userDetails : UserAccount[];
lService : LoginService;
constructor(loginService: LoginService) {
this.lService = loginService;
this.userDetails = this.lService.getUserDetails();
console.log(this.userDetails);
}
ngOnInit() {
}
}
请您张贴完整的组件代码。 –
更新了登录组件。在此先感谢 – siddh
@siddh什么是'getUserDetails()'? – echonax