在遵循每個步驟之後,我仍然面臨同樣的問題。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