0
我有一個服務作爲UserService,它獲取其構造函數的數據,然後通過承諾填充_userData的屬性,這裏是服務:從角色中通過服務調用填充服務獲取數據2
@Injectable()
export class UserService {
private _userData: GrcUser = null;
constructor(private logger: LogService, private http: Http, private noteService: NotificationsService) {
logger.trace('UserService Created');
this.getUserInfo() ;
}
public getUserInfo() {
let userID: string = this.getCookieValue('grcUserId');
let headers = new Headers({ 'X-West-session-token': this.getCookieValue("grcSessionToken") });
if (userID) {
this.http.get(AppConstants.USER_URL + "userInfo/" + userID, { headers: headers })
.map((res: Response) => res.json())
.toPromise()
.then((data: GrcUser) => {
this._userData = data;
if (!data) {
this.noteService.add(new Note('danger', 'Failed to load user
details'));
}
})
.catch((err: any) => {
this.logger.error(err);
this.noteService.add(new Note('danger', 'Error while getting user details'));
Promise.resolve();
});
} else {
this.noteService.add(new Note('danger', 'You are not logged in. Please log in and try again'));
}
}
現在,我想在另一個組件來獲得用戶數據,這是我的嘗試:
export class WorkflowDisplayComponent implements OnInit {
userData: GrcUser;
constructor(private _userService: UserService,) {
}
ngOnInit(): void {
this.userData = this._userService.userData;
}
}
現在我明白爲什麼這是行不通的,我不是瓦亭,直到承諾返回_userData在用戶服務中。我閱讀了一些關於Observable的內容,但我不確定是否要使用它們,以及在這種情況下我可以如何使用它們。
好像我不得不改變我的getUserInfo功能在我userService如果我想使用觀測量
有沒有更好的辦法,我可以做到這一點,而無需重構我的代碼太多