Angular 角6广义/抽象可观测函数
正在处理angular 6应用程序。在这里,我必须从API获取并显示每个页面中的用户列表。 我已经编写了一个功能,它可以完美地工作:Angular 角6广义/抽象可观测函数,angular,rxjs,Angular,Rxjs,正在处理angular 6应用程序。在这里,我必须从API获取并显示每个页面中的用户列表。 我已经编写了一个功能,它可以完美地工作: listUsers() { let result = this.http.get('xyz.com/api/users'); result.toPromise() .then(res => { this.userList = res.json(); }) .catch(err =>
listUsers() {
let result = this.http.get('xyz.com/api/users');
result.toPromise()
.then(res => {
this.userList = res.json();
})
.catch(err => {
this.msgService.add({severity: 'error', summary: 'Internal Server Error',
detail: 'There is an Server Error occurred. Please try again later.'});
} );
}
我的问题是,我希望获取超过10个组件/页面中的用户。我不想在所有这10个组件中重复(biolerplate)上述函数listUsers()
。
我想获取once中央服务中的所有用户,并从每个组件访问它
我该怎么做
对不起,我没有正确回答这个问题。我也找不到任何类似的帖子。如果以前已经有人接过,请给我指一下那个帖子。我将删除这篇重复的帖子。Ngrx Over service injection
单击此处()
希望您能获得此功能,它可以用于解决此问题。这与您的总体架构有关 如果这几乎是唯一让你恼火的情况,我建议你使用
shareReplay
,这样你就可以将观察结果分享给所有消费者
示例:
@Injectable()
export class SomeService {
// ...
public users$: Observable<User[]> = this.http.get('xyz.com/api/users').pipe(
catchError(err => {
this.msgService.add({
severity: 'error',
summary: 'Internal Server Error',
detail: 'There is an Server Error occurred. Please try again later.',
});
throw err;
}),
shareReplay({
bufferSize: 1,
// usually `refCount` should be true so that when all the subscribers
// are not listening anymore, it'll close the observable but here let
// imagine that all your components are not listening to that and then
// later on you come back to it, it will return the previously fetched
// data without fetching it again. If **in that special case** you'd
// prefer to make another request turn that to true
refCount: false,
})
);
// ...
}
@Injectable()
导出类服务{
// ...
public users$:Observable=this.http.get('xyz.com/api/users').pipe(
catchError(err=>{
this.msgService.add({
严重性:“错误”,
摘要:“内部服务器错误”,
详细信息:“发生服务器错误。请稍后再试。”,
});
犯错误;
}),
共享重播({
缓冲区大小:1,
//通常,“refCount”应该为true,以便当所有订阅者
//你不再听了,它会关闭可观察到的,但让我们
//想象一下,您的所有组件都没有听这个,然后
//稍后您返回到它,它将返回以前获取的
//如果**在这种特殊情况下**您将
//更愿意提出另一个请求将其变为真
参考计数:错误,
})
);
// ...
}
这样,如果您没有方法,相同的引用将被共享和使用。多亏了shareReplay
,除非每个人都取消订阅,然后其他人订阅,否则您不会再提出请求。但只要有1个订阅者,不管之后有多少人加入,结果都会被共享
你也可以考虑看看这个图书馆:它会简化你的生活并给予你更多的控制。
另一种选择是开始研究ngrx,因为根据您在路由上的位置提取数据一次(提取一次),然后将其放入本地“存储”中,所有组件都可以访问该存储。但这需要您学习redux/ngrx,这并不简单。如果你的应用程序不断增长,我建议你检查一下,因为它确实很有用,但这取决于你自己,你可以选择你最喜欢的。你可以使用ngxs/store进行状态级管理。创建一个类User-state.ts,它需要以下方法 您可以使用选择器标记从可从所有组件访问的存储中获取用户列表
@Selector()
static userList(state: UserStateModel) {
return state.UserList;
}
const initialState = {
UserList = []
};
// **make data base call to fetch User list**
@Action(UserActions.GetUserList)
getUserList(
{ patchState, dispatch }: StateContext<UserStateModel>,
{ payload }: UserActions.GetUserList
) {
// call the service to backend call.
return this.UserListService
.getPayments(payload)
.pipe(
tap((apiResp: IApiResponse) => dispatch(new UserActions.GetUserListSuccess(apiResp))),
catchError(error => {
return dispatch(new UserActions.UserListFail(error));
})
);
}
// Using **patchState** you can refresh value of UserList in store
@Action(UserActions.GetUserListSuccess)
GetUserListSuccess(
{ patchState }: StateContext<UserStateModel>,
{ payload }: UserActions.GetUserListSuccess
) {
if (!isNullOrUndefined(payload)
&& !isNullOrUndefined(payload.result)
&& !isNullOrUndefined(payload.resultdata)) {
return patchState({
UserList: payload.resultdata.UserList
});
}
return **patchState**({ UserList: initialState.UserList});
}
这回答了你的问题吗?最好考虑NGRXAS,因为我喜欢NGRX,我不认为说“更好地考虑NgRx”在这里是有帮助的。这不是一个银弹,如果不解释它是什么以及它将如何改进用例,可能对操作没有帮助。这也是我的“转到”方法。
export class GetUserList {
static readonly type = '[UserList] Get Payment Details';
}
export class GetUserSuccess {
static readonly type = '[Userlist] Get User List Success';
constructor(public payload?: any) { }
}