Reputation: 73
I am still facing the same problem, after following each steps.
Still Not able to share the data between components via Shared Services.
My Workflow: After login via Login's Service, I wanted to share the UserDetails Response to the About Page.
I have only injected the Login Service in app.module.ts in @NgModule as providers
===Login Component=====
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);
}
}
===Login Service====
@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;
}
}
======About Component=====
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() {
}
}
Upvotes: 1
Views: 207
Reputation: 40647
Change .map(this.extractData);
to
.map((res)=>this.extractData(res));
or .map(this.extractData.bind(this));
your this
is not refering to your component inside the map
function in the first one.
Upvotes: 1