问题描述
使用Angular 7,我有以下服务( StackBlitz示例):
Using Angular 7 I have the following service (StackBlitz Example):
@Injectable({
providedIn: 'root'
})
export class TodoService {
todos: BehaviorSubject<Todo[]> = new BehaviorSubject([
{ id: 1, title: "Buy book", content: "Buy book about angular" },
{ id: 2, title: "Send invoice", content: "Send invoice to client A" }
]);
public get(): Observable<Todo[]> {
return this.todos.asObservable();
}
public create(todo: Todo) {
this.todos.next(this.todos.value.concat(todo));
}
}
此服务由一些组件使用:
This service is used by a few components:
- TodoCreateComponent>创建新的待办事项
- TodoListComponent>显示待办事项列表
- TodoRecentComponent>显示最近的待办事项
每个组件都有自己的模型,该模型以自己的方式从Todo
映射...
Each component has its own model mapped from a Todo
in its own way ...
某些模型使用许多Todo
属性(Title
,Content
),其他模型仅使用一个(Title
)等.
Some models use many Todo
properties (Title
, Content
), others only one (Title
) etc.
在我的 StackBlitz示例中,一个新的Todo
是自动的,添加到待办事项列表中:
On my StackBlitz Example a new Todo
is, automatically, added to the todo list:
客观
现在,我需要用从API获取的数据替换本地数据:
Now I need to replace the local data by data taken from an API:
public get(): Observable<Todo[]> {
return this.httpClient.get<Todo>(`todos`);
}
public create(todo: Todo) {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.httpClient.post(`todos`, todo, { headers: headers });
}
问题
问题是如何集成HttpClient以使所有内容保持同步:
The question is how to integrate HttpClient to get everything in sync:
因此,当创建新的Todo
时,应更新Todos
的列表...
So when a new Todo
is created the list of Todos
should be updated ...
推荐答案
使用通知服务告诉列表组件重新轮询服务器.
Use a notification service to tell the list component to repoll the server.
export class RepollTodosNotificationService {
subject: ReplaySubject<any> = new ReplaySubject();
obs: Observable<any> = this.subject.asObservable;
notify = (data: any) => {
this.subject.next(data)
}
}
使服务单例:
(app.module.ts)
(app.module.ts)
@NgModule({
providers: [RepollTodosNotificationService]
})
在TodoCreateComponent
this.todoSevice.post(myNewTodo)
.subscribe(
result => {
// current callback code
this.repollNotifierService.notify(null); // null or data you want to send
在TodoListComponent
export class TodoListComponent implements OnInit, OnDestroy {
private repollSubscription: Subscription;
constructor(private repollSvc: RepollTodosNotificationService) {}
ngOnInit() {
this.repollSvc.obs.subscribe(() => this.fetchTodos()); // if you transfer data, handle here
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
// methods
}
这篇关于添加新项目时更新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!