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通知組件時,個人資料數據已經改變,並導致他們重新查詢。 –