【问题标题】:Angular : After a post request is made, how to trigger a get request and update a component with the modified values?Angular :发出 post 请求后,如何触发 get 请求并使用修改后的值更新组件?
【发布时间】:2020-07-18 08:10:15
【问题描述】:

getAllSchools() 从后端返回学校列表。当应用程序加载时,我发出一个获取请求并将学校列表加载到一个名为学校的数组中。

addSchool() 添加一所新学校

每次addSchool() 完成时,我都想刷新学校数组以包含新学校。我该怎么做?

school-service.ts

  getAllSchools(): Observable<ISchool[]> {
    return this.http.get<ISchool[]>(this.url);
  }


  addSchool(school: ISchool): Observable<ISchool> {
    this.schoolsSubject$.next();
    return this.http.post<ISchool>(this.url, school, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    });
  }

app-component.ts

  ngOnInit(): void {
    this.getSchools();
  }


  getSchools(): void {
    this.schoolService.getAllSchools().subscribe({
      next: schools => {
        this.schools = schools;
        this.filteredSchools = schools;
      },
      error: err => this.errorMessage = err
    });
  }

add-school-component.ts

  onSubmit(form: NgForm) {
    this.schoolService.addSchool(this.model)
      .subscribe(
        (data: ISchool) => console.log(data),
        (err: any) => console.log(err)
      ); 
  }

【问题讨论】:

  • add-school-component.ts 是 app-component.ts 的子项吗?

标签: angular http rxjs


【解决方案1】:

您可以使用BehaviorSubject 保留数据并使用tap 再次调用

export class YourService {
  private _schools: BehaviorSubject<ISchool[]>;

  constructor(
    private http: HttpClient,
  ) {
    this._schools = new BehaviorSubject([]);
  }

  getAllSchools(): Observable<ISchool[]> {
    this._getAllSchools();

    return this._schools.asObservable();
  }

  addSchool(school: ISchool): Observable<ISchool> {
    return this.http.post<ISchool>(this.url, school, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    }).pipe(
      // after successfully adding a school you call once again get all schools
      tap(() => this._getAllSchools()),
    );
  }

  private _getAllSchools(): void {
    this.http.get<ISchool[]>(this.url).subscribe(
      schools => this._schools.next(schools),
    );
  }
}

【讨论】:

    【解决方案2】:

    在 add-school-component.ts 中

      @Output() newSchool: EventEmitter<any> = new EventEmitter();
    
      onSubmit(form: NgForm) {
        this.newSchool.emit(this.model);
      }
    

    在 app-component.html 中

    <app-add-school (newSchool)='addNewSchool($event)></app-add-school>
    

    在 app-conponent.ts 中

      addNewSchool(newSchool) {
        this.schoolService.addSchool(newSchool)
           .subscribe(
             (data: ISchool) => console.log(data),
             (err: any) => console.log(err)
           );
    
           this.getSchools();
      }
    

    【讨论】:

    • schools 数组是应用程序组件,addschool 在学校服务中。所以,不能那样做..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 2021-09-15
    • 2021-09-07
    相关资源
    最近更新 更多