这种情况下,我希望在NavMenuComponent中有一个带有博客的组合框(select)。这是关于快速导航体验。
目前我有第二个数组blogs: IBlogs[],这是不好的做法,但不管怎样。
我现在的问题是,当我添加/删除任何博客时,combobox都不会更新。这是因为我使用的是BlogComponent>blogs[]而不是NavMenuComponent>blogs[]
我必须努力刷新才能让它工作!还有更好的方法吗?我可以从另一个组件强制更新数组吗?没有共享服务
我可以将它们放到共享服务中,但我不喜欢这个想法。因为在BlogComponent中,我将不得不使用sharedService.getBlogs()而不是blogService.getBlogs()。
有什么想法吗?
发布于 2017-07-15 00:48:54
举个例子:
export enum BlogAction{
CREATE,
DELETE
}
export Blog{
id: number;
name: string;
}
export class BlogActionModel{
action: BlogAction;
blog: Blog;
}
@Injectable()
export class BlogService{
private blogPoster: Subject<BlogActionModel> = new Subject<BlogActionModel>();
public $blogPosted: Observable<BlogActionModel> = this.blogPoster.asObservable();
create(blog: Blog): void{
this.blogResource.saveToBackend(blog); //do save routine
this.blogPoster.next({
action: BlogAction.CREATE,
blog: blog
});
}
//implement `update` and `delete` actions in same way
}
@Component({})
export class NavMenuComponent implements OnInit{
private blogs: Blog[] = [];
constructor(private blogService: BlogService){}
ngOnInit(): void{
this.blogService.$blogPosted.subscribe((blogAction: BlogActionModel) => {
if(blogAction.action === BlogAction.CREATE){
this.blogs.push(blogAction.blog);
}else if(blogAction.action === BlogAction.DELETE){
//do delete
}else{
//do update
}
});
}
}https://stackoverflow.com/questions/45107794
复制相似问题