使用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));
}
}
此服务由一些组件使用:
每个组件都以自己的方式从Todo
映射出自己的模型...
某些模型使用许多Todo
属性(Title
,Content
),其他模型仅使用一个属性(Title
)等等。
在我的StackBlitz Example上,自动将新的Todo
添加到待办事项列表:
客观
现在,我需要用从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
的列表应更新...
答案 0 :(得分:1)
使用通知服务告诉列表组件重新轮询服务器。
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
}
答案 1 :(得分:0)
一种保持同步的方法是使用RxJS运算符tap
根据API的响应来更新BehaviorBject,例如:
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 ))
}