添加新项目时更新列表

时间:2019-05-13 17:05:57

标签: angular typescript angular-httpclient

使用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));
  }

}

此服务由一些组件使用:

  1. TodoCreateComponent>创建新的待办事项
  2. TodoListComponent>显示待办事项列表
  3. TodoRecentComponent>显示最近的待办事项

每个组件都以自己的方式从Todo映射出自己的模型...

某些模型使用许多Todo属性(TitleContent),其他模型仅使用一个属性(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的列表应更新...

2 个答案:

答案 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 ))
}