Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何从其他组件更新数据_Angular_Typescript - Fatal编程技术网

Angular 如何从其他组件更新数据

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

我使用的是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.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指令过于频繁地检查和更改特定变量。我会以不同的方式解决你的问题;在“英雄”组件中引用这两个组件可以使您从细节到英雄更新列表。