如何调用组件来更新数据?

时间:2016-07-04 09:49:34

标签: rest angular

我有一个包含2个子组件的主要组件(更新,配置文件)。

在更新组件上,我有一个包含多个输入字段的表单。当我提交表单时,配置文件部分信息应在成功请求后更新。

问题是,成功请求后配置文件信息不会更新。

那么,如何调用配置文件组件来刷新更新的数据?我成功请求后尝试拨打电话,但没有运气。

顺便说一句,父服务看起来像:

@Injectable()
export class AvailabilityService {

  constructor(private http: Http) {
  }

  getProfile() {
    return this.http.get(API_URL + '/user/profile')
      .map(this.extractData)
      .catch(this.handleError);
  }

  freeOwnersParking(availableDates: AvailableDates) {
    let domain = API_URL + '/parking/availability';
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(availableDates);
    return this.http.put(domain, body, options)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body;
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    return Observable.throw(errMsg);
  }

}

更新

获取个人资料:

getProfile() {
    this.availabilityService.getProfile()
      .subscribe(
        profile =>this.profile = profile,
        error => this.errorMessage = <any>error
      );
  }

更新个人资料:

freeOwnersParking() {
    this.availabilityService.freeOwnersParking(this.availableDates)
      .subscribe(
        response => this.availabilityService.getProfile(),
        error => this.errorMessage = error
      );
  }

1 个答案:

答案 0 :(得分:0)

您需要利用它们之间的共享服务来通知配置文件组件。

例如,一个带有observable / subject的UpdateProfileService。在这种情况下,配置文件组件可以订阅它以进行通知。

这是服务:

@Injectable()
export class UpdateProfileService {
  profileUpdated:Subject<boolean> = new Subject();

  (...)

  updateProfile(profile:any) {
    return this.http.put('http://...', profile)
            .map(res => {
              this.profileUpdated.next(true);
              return res.json();
            });
  }
}

并在个人资料组件中:

@Component({
  (...)
})
export class ProfileComponent {
  constructor(private service:UpdateProfileService) {
    this.service.profileUpdated.subscribe(() => {
      // Update bound data for profile
    });
  }
}