2016-11-18 90 views
0

我有一個父組件,控制兩個孩子。 FormChild是將教師添加到列表並將其編輯的輸入表單,ListChild是使用FormChild輸入/編輯的教師列表。期望的行爲(我只能部分地工作)是在ListChild中反映的FormChild中進行更改。角2:從表單組件兄弟更新列表組件

FormChild有兩種模式;編輯並添加。標誌確定表單是否具有「添加」值或「編輯」值。當標誌(編輯)爲真時,調用'editTeacher'服務方法,當它爲false時,調用'addTeacher'服務方法。

public emitChangeNotification() { 
    this.changeNotifier.emit(); 
} 

teacherAddEdit(event) { 

    if (!this.editing) { 
    this._userService.addTeacher(this.userItem) 
     .subscribe(
     nextItem=> this.nextItemMsg = nextItem 
     , error => this.errorMsg = <any> error 
     ,()=>this.emitChangeNotification() 
    ); 
    } 
    else { 
    this._userService.editTeacher(this.userItem) 
     .subscribe(
     nextItem=> this.nextItemMsg = nextItem 
     , error => this.errorMsg = <any> error 
     ,()=>this.emitChangeNotification() 
    ); 
    } 
    this.initForm(); 
} 

請注意,在添加和編輯的情況下,對服務的調用都幾乎相同。這裏應該發生的事情是,完成後,observable將調用這個.EmitChangeNotification,它會冒泡到父級,然後導致ListChild更新。

問題是,ListChild只更新添加,而不是編輯!用f12跟蹤代碼,我看到在'add'情況下,this.EmitChangeNotification被調用;但不在編輯的情況下。這只是web ui的一個問題;後端正在調用,並且更改正在數據庫中保持不變。

在服務的服務調用是除了被稱爲特定後端網絡API方法相同:

addTeacher(userToCreate:CreateUser) 
{ 
    let Url = this.BASEURL + '/accounts/create'; 
    let headers = new Headers({ 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }); 
    let options = new RequestOptions({ headers: headers }); 
    let body = JSON.stringify(userToCreate); 
    return this._http.post(this._createUserUrl, body, options).map((res: Response) => res.json()); 
} 

editTeacher(userToChange:CreateUser) 
{ 
    let Url = this.BASEURL + '/updateTeacher/' + userToChange.UserId; 
    let headers = new Headers({ 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }); 
    let options = new RequestOptions({ headers: headers }); 
    let body = JSON.stringify(userToChange); 
    return this._http.post(Url, body, options).map((res: Response) => res.json()); 
} 

本來,在該服務的「editTeacher」使用_http.put;我改變了這個_http.post;但這並沒有幫助。我「已經看了一些例子,看起來這應該只是工作...我在做什麼錯在事先

感謝

編輯:另一條線索......似乎」在完成編輯‘案例」的訂閱回調中不被稱爲在所有’我取代:

,()=>this.emitChangeNotification() 

,()=>console.log('tell someone') 

和在編輯時添加而不是時,日誌顯示消息。

我看不出他們是如何不同......

+0

你如何知道在編輯'emitChangeNotification'時不會調用?你是否收到任何錯誤? – ranakrunal9

+0

我可以通過在chrome上單擊f12的代碼來查看它。我沒有直接將changeNotifier.Emit()作爲訂閱的第三個參數,我寫了單獨的函數emitChangeNotification()。我在該函數中設置了斷點,添加時會中斷,但在編輯時不會。 – user2785918

回答

0

要回答我的問題....

事實上,Web UI的差異不顯着。

不同之處在於角度服務所調用的web api調用。看起來完成調用需要觸發的事情是API必須返回一些東西。

在編輯的情況下,我什麼也沒有返回,只有一個HTTP.OK,但是當我改變這個返回一個用戶對象時,回調會觸發,列表更新。在我看來,這是寫在某個地方的好消息,所以我在這裏爲後人提供這個信息,希望它能夠爲別人挽救一些悲傷。