添加新项目时更新列表
Update list when new item is added
使用 Angular 7 我有以下服务 (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));
}
}
此服务由几个组件使用:
- TodoCreateComponent > 创建新的 todo
- TodoListComponent > 显示待办事项列表
- TodoRecentComponent > 显示最近的待办事项
每个组件都有自己的模型,从 Todo
以自己的方式映射...
一些模型使用许多 Todo
属性(Title
、Content
),其他模型仅使用一个(Title
)等
在我的 StackBlitz Example 上,一个新的 Todo
自动添加到待办事项列表中:
Objective
现在我需要用取自 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 以同步所有内容:
因此,当创建新的 Todo
时,Todos
的列表应该更新 ...
保持同步的一种方法是使用 RxJS 运算符 tap
根据 API 的响应更新您的 BehaviorSubject,例如:
public get(): Observable<Todo[]> {
return this.httpClient.get<Todo>(`todos`)
.pipe(tap(todo => this.todos.next(todos)))
}
或
public create(todo): Observable<Todo[]> {
return this.httpClient.post<Todo>(`apiUrl`, todo)
.pipe(tap(todo => // do something with the todo ))
}
使用通知服务告诉列表组件重新轮询服务器。
export class RepollTodosNotificationService {
subject: ReplaySubject<any> = new ReplaySubject();
obs: Observable<any> = this.subject.asObservable;
notify = (data: any) => {
this.subject.next(data)
}
}
将服务设为单例:
(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
}
使用 Angular 7 我有以下服务 (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));
}
}
此服务由几个组件使用:
- TodoCreateComponent > 创建新的 todo
- TodoListComponent > 显示待办事项列表
- TodoRecentComponent > 显示最近的待办事项
每个组件都有自己的模型,从 Todo
以自己的方式映射...
一些模型使用许多 Todo
属性(Title
、Content
),其他模型仅使用一个(Title
)等
在我的 StackBlitz Example 上,一个新的 Todo
自动添加到待办事项列表中:
Objective
现在我需要用取自 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 以同步所有内容:
因此,当创建新的 Todo
时,Todos
的列表应该更新 ...
保持同步的一种方法是使用 RxJS 运算符 tap
根据 API 的响应更新您的 BehaviorSubject,例如:
public get(): Observable<Todo[]> {
return this.httpClient.get<Todo>(`todos`)
.pipe(tap(todo => this.todos.next(todos)))
}
或
public create(todo): Observable<Todo[]> {
return this.httpClient.post<Todo>(`apiUrl`, todo)
.pipe(tap(todo => // do something with the todo ))
}
使用通知服务告诉列表组件重新轮询服务器。
export class RepollTodosNotificationService {
subject: ReplaySubject<any> = new ReplaySubject();
obs: Observable<any> = this.subject.asObservable;
notify = (data: any) => {
this.subject.next(data)
}
}
将服务设为单例:
(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
}