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如果我想使用观测量
有没有更好的办法,我可以做到这一点,而无需重构我的代码太多