使父组件调用角度为2的函数

时间:2016-11-17 13:31:18

标签: angular angular2-services

我有父组件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);
}

1 个答案:

答案 0 :(得分:0)

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