【发布时间】:2017-08-27 07:16:18
【问题描述】:
执行完每个步骤后,我仍然面临同样的问题。
仍然无法通过共享服务在组件之间共享数据。
我的工作流程:通过登录服务登录后,我想将 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() {
}
}
【问题讨论】:
-
请您发布完整的组件代码。
-
更新了登录组件。提前致谢
-
@siddh
getUserDetails()是什么? -
对不起,我的错误,getUserDetails() 返回返回 this.userAccount;我已经更新了 login.service.ts
标签: angular typescript