Angular 如何从其他组件更新数据
我使用的是angular 6.0,这是我的一些组件的结构Angular 如何从其他组件更新数据,angular,typescript,Angular,Typescript,我使用的是angular 6.0,这是我的一些组件的结构 heroes |--hero-detail | |--hero-detail.component.ts|htmlcss|spec.ts |--hero-list | |--hero-list.component.ts|html|css|spec.ts |--shared | |--hero-button.component.ts|html|css|spec.ts | |--hero.model.ts | |--hero.serv
heroes
|--hero-detail
| |--hero-detail.component.ts|htmlcss|spec.ts
|--hero-list
| |--hero-list.component.ts|html|css|spec.ts
|--shared
| |--hero-button.component.ts|html|css|spec.ts
| |--hero.model.ts
| |--hero.service.ts|spec.ts
|--heroes.component.ts|html|css|spec.ts
|--heroes.module.ts
|--heroes-routing.module.ts
我正在从英雄细节
创建一个新的英雄
,我的问题是,在我从英雄细节
添加一些英雄
后,是否可以在英雄列表
中更新英雄的列表
这就是我添加英雄的方式
英雄细节
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;
});
}
<div class="col-sm-12" *ngIf="isUpdateSource; then doUpdateSource();">
<mat-table #table [dataSource]="dataSource" matSort>..</mat-table>
</div>
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'))
);
}
}
export class HeroListComponent {
hasData: boolean;
constructor() {
hasData = true;
}
}
我的英雄列表
使用的是mat表
,这就是我获取数据的方式
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()
后,我尝试记录一些结果,但它是垃圾邮件
英雄列表.html
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;
});
}
<div class="col-sm-12" *ngIf="isUpdateSource; then doUpdateSource();">
<mat-table #table [dataSource]="dataSource" matSort>..</mat-table>
</div>
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'))
);
}
}
export class HeroListComponent {
hasData: boolean;
constructor() {
hasData = true;
}
}
您从未将this.heroService.updateSource设置为false,从而使ngIf不断地进行垃圾邮件更新。好的,正如卡斯滕所说,我需要将this.heroService.updateSource
设置为false
以停止垃圾邮件发送日志
,但我会遇到这个错误
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'
为了解决这个问题,我在应用程序中添加了一些逻辑
我创建了一个附加的hasData
变量,并始终设置为true
,以始终显示表
英雄列表.component.ts
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;
});
}
<div class="col-sm-12" *ngIf="isUpdateSource; then doUpdateSource();">
<mat-table #table [dataSource]="dataSource" matSort>..</mat-table>
</div>
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'))
);
}
}
export class HeroListComponent {
hasData: boolean;
constructor() {
hasData = true;
}
}
然后我更改了我的英雄列表.component.html
<div class="col-sm-12" *ngIf="hasData||isUpdateSource">
<mat-table #table [dataSource]="dataSource" matSort>..</mat-table>
</div>
你也可以在这里发布你的服务文件吗?@PardeepJain是对的。发布你的服务文件。我更新了我的问题,很抱歉我忘记了服务。什么不适用于getHeroList()
?可能您还需要编写this.getHeroList()
(添加了此项)不,我的意思是调用该函数不起作用。我尝试在doUpdateSource()中设置this.heroService.updateSource=false
,下面是我得到的结果ExpressionChangedTerrithasbeenCheckedError:检查后,表达式已更改。上一个值:“ngIf:true”。当前值:“ngIf:false”。
@Jer这意味着ngIf指令过于频繁地检查和更改特定变量。我会以不同的方式解决你的问题;在“英雄”组件中引用这两个组件可以使您从细节到英雄更新列表。