【发布时间】:2019-07-27 11:06:58
【问题描述】:
我很困惑,这可能是我在学习 rxJS 和 Observables 时一直采用的方法。
前言
我们的应用程序使用 Angular 连接到我们的公共 API 层 (C#)。从我的 ASYNC 调用返回的对象类型是 Observable。该流被传递给循环遍历项目的子组件。同样的流还允许用户添加 NoteDto 类型的新笔记或编辑笔记。理想情况下,当这些操作完成后,便笺列表将反映更新后的更改,而无需再次调用相同的服务调用来获取便笺。
代码
[notes.component.html]
<div *ngIf="(notes$ | async)?.items as notes; else loading">
<note-card [noteData]="notes" (noteClick)="editNote($event)"></note-card>
</div>
<ng-template #loading>
<div class="notes__container">
<div class="note-card">
<div class="note-card__primary-action">
<div class="note-card__head">
<h2 class="note-card__title note-card-typography--headline1 text-center">Loading...</h2>
</div>
</div>
</div>
</div>
</ng-template>
[notes.component.ts]
import ...
@Component({
...
})
export class NotesComponent extends AppComponentBase implements OnInit {
constructor(
...
private _noteService: NoteServiceServiceProxy
) {
super(injector);
}
public notes$: Observable<ListResultDtoOfNoteDto>;
public userId: number;
...
ngOnInit() {
...
this.getNotes();
...
}
getNotes(): void {
/*
Binding to ASYNC pipe; which doesn't need a subscription since it is automatic?
Returns type: Observable<ListResultDtoOfNoteDto> which is an array of NoteDto
*/
this.notes$ = this._noteService.getUserNotes(this.userId, null);
...
}
...
public saveNote(note: NoteDto, mode: string) {
if (mode === 'new') {
this._noteService.addNote(note).subscribe(() => {
this.cleanUp();
this.getNotes();
this.notify.info(this.l('SavedNoteSuccessfully'));
});
}
...
}
}
在子级中减去 clickEvent 的所有功能都发生在父级中。它会加载一个表单(反应式表单方法),该表单可以记录新笔记并保存或编辑旧笔记以进行更新。
我的问题
我只是想要一种方法来保存笔记并更新列表,而无需在添加新笔记时在订阅中再次调用 this.getNotes()。
(如果需要,我可以提供更多详细信息!)
编辑:目前忘记显示保存方法
【问题讨论】:
-
您的笔记服务是否包含直接的 api 调用?如果您不想再次调用 getNotes,则需要将数据存储在服务中并在 add 调用完成后更新该数据(通常使用 HTTP POST 创建对象,您将获取创建的对象,因此您可以将此对象添加到包含您的数据的服务中)。如果您的应用程序(许多组件)严重依赖此数据基础,则可能值得一试github.com/ngrx/store,否则您可以编写一个包含您的数据的单例服务。
-
我这不是在我的 getNotes() 方法中的 this.notes$ = this._noteService.getUserNotes() 技术上完成的吗?另外,如果您查看我的 SaveNotes() 方法,我认为我没有正确使用 ASYNC,因为我再次调用 GetNotes() 并再次重铸该服务调用
标签: angular rxjs observable