[英]Angular: Components do not get updated with data from public service variable
由于此应用程序中没有很多Source
项目,所以我认为我会聪明一点,设计一个也可以充当存储库的服务,并在该服务添加,更新或删除项目时在内部进行更新。
为了在第一次使用时填充存储库,然后我的主要组件通过订阅一次运行listSources()
。 所有其他组件都注入了服务,在其模板中,我使用let source of sourceService.sources
来获取源。
但是,当我通过addSource()
或任何其他方式更改源时,这些更改未反映在我的其他组件中。 我也尝试过使用一个主题,但是这变得更加令人困惑,并且对我也不起作用。
有人知道我在做什么错吗?
这是服务:
export class SourceService { // truncated for brevity
public sources: Source[] = [];
constructor( ) { }
public listSources(): Observable<Source[]> {
// if sources are already loaded, just return from memory
if (this.sources.length > 0) {
return of(this.sources);
}
return this.http.get<Source[]>(sourceUrl, httpOptions).pipe(
tap(sources => {
sources.forEach((source, index, sources) => {
this.sources.push(source);
});
});
}
public addSource(source: Source): Observable<Source> {
return this.http.post<Source>(sourceUrl, source, httpOptions).pipe(
tap(data => {
// update memory
this.sources.push(Object.assign(new Source(), Source.EMPTY_MODEL));
})
);
}
在其他地方,注入了sourceService
的组件具有以下模板:
<mat-option *ngFor="let source of sourceService.sources" [value]="source.id">{{ source.title }}</mat-option>
尝试这个
export class SourceService { // truncated for brevity
public sources: Source[] = [];
public sources$ = new BehavoiurSubject<Source[]>([]);
constructor( ) { }
public listSources(): Observable<Source[]> {
// if sources are already loaded, just return from memory
if (this.sources.length) {
this.sources$.next(this.sources);
return of(this.sources);
}
return this.http.get<Source[]>(sourceUrl, httpOptions).pipe(
tap(sources => {
sources.forEach((source, index, sources) => {
this.sources.push(source);
});
this.sources$.next(this.sources);
});
}
public addSource(source: Source): Observable<Source> {
return this.http.post<Source>(sourceUrl, source, httpOptions).pipe(
tap(data => {
// update memory
this.sources.push(Object.assign(new Source(), Source.EMPTY_MODEL));
this.sources$.next(this.sources);
})
);
}
在你的组件中
<ng-container *ngIf="sourceService.sources$ | async as sources>
<mat-option *ngFor="let source of sources" [value]="source.id">{{ source.title }}</mat-option>
</ng-container >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.