2016-11-17 32 views
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); 
} 
+1

我會使用一個observable通知組件時,個人資料數據已經改變,並導致他們重新查詢。 –

回答

0

感謝約翰·貝爾德我能創造一個包含UserServiceupdated = new BehaviorSubject<boolean>(false)該如果配置文件被編輯或沒有信息。當我從子組件編輯配置文件時,我將該主題的下一個值設置爲true this.updated.next(true)。另一方面,我訂購了UserComponent的主題以及主題的價值變化,我解僱了更新數據的getProfile()函數。

相關問題