0
我有父组件UserComponent
其子路由很少。我希望能够从任何子路由中调用UserComponent
中的函数。这是因为UserComponent
和例如它的子组件ProfileComponent
都使用UserService
中的函数来获取它们需要显示的数据,但是当我编辑ProfileComponent
中的数据时,数据不会在UserComponent
中刷新(因为它在实例创建后获取所有数据(ngOnInit()),我想它没有听更改)。使父组件调用一个函数angular 2
CODE 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
);
}
CODE 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
);
}
CODE 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);
}
我会使用一个observable通知组件时,个人资料数据已经改变,并导致他们重新查询。 –