让父组件调用一个函数angular 2

Make parent component call a function angular 2

我的父组件 UserComponent 几乎没有子路由。我希望能够从任何子路由调用 UserComponent 中的函数。那是因为 UserComponent 和例如它的子组件 ProfileComponent 使用 UserService 中的函数来获取它们需要显示的数据,但是当我编辑 ProfileComponent 中的数据时,数据UserComponent 中没有刷新(因为它在创建实例后获取所有数据( ngOnInit() ),我猜它没有监听更改)。

代码 UserComponent:

error: string;
user: IProfile | {};

constructor(private router: Router, private userService: UserService) {}

ngOnInit() {
  this.getUser();
}

getUser() {
  this.userService.getProfile().subscribe(
    response => this.user = response,
    error => this.error = error
  );
}

代码 ProfileComponent:

user: IProfile | {};
error: string;

constructor(private userService: UserService) {}

ngOnInit() {
  this.userService.getProfile().subscribe(
    response => {
      this.user = response;
    },
    error => this.error = error
  );
}

update() {

  ...

  this.userService.updateProfile(data).subscribe(
    response => console.log(response),
    error => this.error = error
  );  
}

代码 UserService:

  private profileURL = 'http://localhost:4042/api/v1/profile';

  constructor(private http: Http) {}

  getProfile(): Observable<Object> {
    let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.profileURL, options)
                    .map(this.handleResponse)
                    .catch(this.handleError);
}

private handleResponse(data: Response): IProfile | {} {
  return data.json() || {};
}

private handleError (error: Response | any): Observable<Object> {

  ...

  return Observable.throw(errMsg);
}

updateProfile(data): Observable<Object> {
  let body = JSON.stringify(data);
  let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token'), 'Content-Type': 'application/json;charset=utf-8' });
  let options = new RequestOptions({ headers: headers });

  return this.http.patch(this.profileURL, body, options)
             .map((response: Response) => response)
             .catch(this.handleError);
}

感谢 John Baird,我能够在 UserService 中创建一个 updated = new BehaviorSubject<boolean>(false),其中包含配置文件是否被编辑的信息。当我从子组件编辑配置文件时,我将该主题的下一个值设置为 true this.updated.next(true)。另一方面,我订阅了该主题以更改 UserComponent 并且在主题的值更改时我触发了更新数据的 getProfile() 函数。