以下是有关我的项目的一些信息:
userId
。post.data
和post.user.name
有没有办法急于用帖子加载用户数据?
这个问题的最佳解决方案是什么?
这就是post.model
的样子:
import { User } from './user.model';
export class Post {
userId: number;
id: number;
title: string;
body: string;
user?: User;
}
我没有获得包含帖子项目的整个用户对象。我只收到userIds。
编辑:这是我获取和呈现帖子的方式:
post.effects.ts
@Injectable()
export class PostEffects {
@Effect()
posts$: Observable<Action> = this.actions$
.ofType(postActions.LOAD_LIST)
.debounceTime(300)
.startWith(new postActions.LoadListAction())
.switchMap(() => {
return this.postsService.all()
.map((posts: Post[]) => new postActions.LoadListSuccessAction(posts))
.catch(error => of(new postActions.LoadListFailAction(error)));
});
constructor(
private actions$: Actions,
private postsService: PostsService
) { }
}
posts.component.ts
export class PostsComponent {
posts$: Observable<Post[]>;
loaded$: Observable<boolean>;
constructor(private store: Store<State>) {
this.posts$ = store.select(rootReducers.getPostItems);
this.loaded$ = store.select(rootReducers.getPostLoaded);
}
}
posts.component.html
<div class="content">
<app-post-list [posts]="posts$ | async"></app-post-list>
</div>
<!-- /.content -->
编辑2:发布缩减器文件内容
post.reducer.ts
export function reducer(state = initialState, {type, payload}: postActions.Actions): State {
switch (type) {
case postActions.LOAD_LIST: {
return Object.assign({}, state, {
loading: true
});
}
case postActions.LOAD_LIST_SUCCESS: {
return {
loaded: true,
loading: false,
items: payload,
selectedItem: state.selectedItem
};
}
default: {
return state;
}
}
}
答案 0 :(得分:0)
我找到了解决方案,但我认为它并不完美。
我认为这会很慢,但事实并非如此。这样我只能制作两个http请求。帖子和用户请求。
目前我无法找到更好的解决方案。如果你有一个,我很乐意整合它。
修改强>
嗯,我想我找到了解决方案:Handle Multiple Angular 2 Models in ngrx with Computed Observables,
在本文中,我找到了代码段,它对我有用:
export class UsersItemsService {
constructor(private store: Store<AppStore>) { }
getUsersItems(): Observable<UserItems[]> {
const users$: Observable<User[]> = this.store.select('users');
const items$: Observable<Item[]> = this.store.select('items');
return Observable.combineLatest(users$, items$, (users, items) => {
return users.map(user => Object.assign({}, user, {
items: items.filter(item => item.userId === user.id)
}));
});
}
}