在完成每个步骤后,我仍然面临同样的问题。
仍然无法通过共享服务在组件之间共享数据。
我的工作流程:通过登录服务登录后,我想分享关于关于页面的UserDetails响应。
我只在@NgModule的app.module.ts中注册了登录服务作为提供者
===登录组件=====
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() {
}
}
答案 0 :(得分:1)
更改.map(this.extractData);
到
.map((res)=>this.extractData(res));
或.map(this.extractData.bind(this));
您的this
未在第一个map
函数中引用您的组件。