我使用角度6.0,这是我的一些组件的结构。
hero
我正在从hero-detail
创建一个新的hero
,我的问题是,在添加一些{hero-list
后,是否可以更新hero
中的hero-detail
列表1}}来自hero-detail
?
这就是我添加英雄的方式
onSubmit() {
add();
}
add(): void {
this.heroService.addHero( this.heroForm.value as Hero)
.subscribe(hero => {
this.heroService.heroes.push(hero);
// This is how I notify the list.
this.heroService.updateSource = true;
});
}
hero-list
我的mat-table
正在使用getHeroList(): void {
this.heroService.getHeroes().subscribe(
result => {
this.heroService.heroes = result;
this.dataSource = new MatTableDataSource(this.heroService.heroes);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
);
}
// This is how I check if the hero is successfully added.
get isUpdateSource(): {
return this.heroService.updateSource;
}
doUpdateSource(): void {
console.log("update source");
// getHeroList(); // This is not working.
}
,这就是我获取数据的方式。
isUpdateSource()
但在获得hero-list.html
之后,我尝试记录一些结果,但这是垃圾邮件......
<div class="col-sm-12" *ngIf="isUpdateSource; then doUpdateSource();">
<mat-table #table [dataSource]="dataSource" matSort>..</mat-table>
</div>
hero.service
export class HeroService {
updateSource: boolean;
private heroesUrl = 'api/heroes';
constructor(
private http: HttpClient,
) { }
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log('${operation} failed: ${error.message}');
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
private log(message: string) {
console.log(message);
}
/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
}
{{1}}
答案 0 :(得分:1)
您永远不会将this.heroService.updateSource设置为false,从而使ngIf不断进行垃圾邮件更新。