从通过 angular 中的服务调用填充的服务获取数据 2
Getting a data from a service which is populate through a service call in angular 2
我有一个 UserService 服务,它在其构造函数上获取数据,然后通过承诺填充它的 属性 of _userData,这是服务:
@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'));
}
}
现在,我想在另一个组件中获取 userData,我就是这样尝试的:
export class WorkflowDisplayComponent implements OnInit {
userData: GrcUser;
constructor(private _userService: UserService,) {
}
ngOnInit(): void {
this.userData = this._userService.userData;
}
}
现在我明白为什么这不起作用了,我不会等到用户服务中的承诺 returns _userData。我在 Observable 上阅读了一些内容,但我不太确定是否要使用它们以及在这种情况下如何使用它们。
如果我想使用 Observables,似乎我必须更改 userService 中的 getUserInfo 函数
有没有更好的方法可以做到这一点,而无需过多重构我的代码
您不应将 http observable 转换为 toPromise()。在这种情况下,您必须多播您的 http observable 并将其缓存在您的服务中。
@Injectable()
export class UserService {
private _userData: GrcUser = null;
private httpObservable: Observable;
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) {
if(this.httpObservable){
return this.httpObservable;
} else if(this._userData){
return Observable.of(this._userData);
} else {
this.httpObservable = this.http.get(AppConstants.USER_URL + "userInfo/" + userID, { headers: headers })
.map((res: Response) => res.json())
.do((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'));
return Observable.of(false);
}).share();
return this.httpObservable;
}
} else {
this.noteService.add(new Note('danger', 'You are not logged in. Please log in and try again'));
return return Observable.of(false);
}
}
在代码中,请注意 .share()
方法。这将多播您的可观察对象。
在您的任何其他组件中:
export class WorkflowDisplayComponent implements OnInit {
userData: GrcUser;
constructor(private _userService: UserService,) {
}
ngOnInit(): void {
this._userService.getUserInfo()
.subscribe((userData: any) => {
if(userData !== false) {
this.userData = userData;
}
});
}
}
这样一来,您只需进行一个 http 调用并将其缓存在服务中,所有后续调用都将从服务的存储变量中得到服务。
我有一个 UserService 服务,它在其构造函数上获取数据,然后通过承诺填充它的 属性 of _userData,这是服务:
@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'));
}
}
现在,我想在另一个组件中获取 userData,我就是这样尝试的:
export class WorkflowDisplayComponent implements OnInit {
userData: GrcUser;
constructor(private _userService: UserService,) {
}
ngOnInit(): void {
this.userData = this._userService.userData;
}
}
现在我明白为什么这不起作用了,我不会等到用户服务中的承诺 returns _userData。我在 Observable 上阅读了一些内容,但我不太确定是否要使用它们以及在这种情况下如何使用它们。
如果我想使用 Observables,似乎我必须更改 userService 中的 getUserInfo 函数
有没有更好的方法可以做到这一点,而无需过多重构我的代码
您不应将 http observable 转换为 toPromise()。在这种情况下,您必须多播您的 http observable 并将其缓存在您的服务中。
@Injectable()
export class UserService {
private _userData: GrcUser = null;
private httpObservable: Observable;
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) {
if(this.httpObservable){
return this.httpObservable;
} else if(this._userData){
return Observable.of(this._userData);
} else {
this.httpObservable = this.http.get(AppConstants.USER_URL + "userInfo/" + userID, { headers: headers })
.map((res: Response) => res.json())
.do((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'));
return Observable.of(false);
}).share();
return this.httpObservable;
}
} else {
this.noteService.add(new Note('danger', 'You are not logged in. Please log in and try again'));
return return Observable.of(false);
}
}
在代码中,请注意 .share()
方法。这将多播您的可观察对象。
在您的任何其他组件中:
export class WorkflowDisplayComponent implements OnInit {
userData: GrcUser;
constructor(private _userService: UserService,) {
}
ngOnInit(): void {
this._userService.getUserInfo()
.subscribe((userData: any) => {
if(userData !== false) {
this.userData = userData;
}
});
}
}
这样一来,您只需进行一个 http 调用并将其缓存在服务中,所有后续调用都将从服务的存储变量中得到服务。