2017-05-06 57 views
1

我有 服務如何在更改任何項目後更新Angular2(v.4)中的列表?

modCountry(country: Country): Observable<any> { 
    let headers = new Headers({'content-type':'application/json;charset=utf-8'}); 
    let options = new RequestOptions({headers: headers}); 
    return this.http 
     .post('http://localhost/my-app/src/core/literature/model/m_country.php', { country }, options) 
     .map(this.extractData) 
     .catch(this.handleError); 
    } 
    getCountries(viewName: string): Observable<Country[]> { 
    return this.http 
     .get(this.viewPath+viewName) 
     .map(this.extractData) 
     .catch(this.handleError); 
    } 

部件

getCountries(): void { 
    this.literatureService.getCountries('v_country.php') 
     .subscribe(countries => this.countries = countries); 
    } 
    countrySubmit(): void { 
    this.literatureService.modCountry(this.countryEditForm.value) 
     .subscribe((country) => { 
     console.log(country); 
     }); 
    this.visibility.countryE = 'inactive'; 
    this.visibility.countryL = 'active'; 
    getCountries(); 
    } 

模板

<div id="country_mod"> 
    <h1 (click)="toggleForm('country');">country</h1> 
    <fieldset id="country_list" [@countryChangedL]="visibility.countryL"> 
    <form> 
     <div class="list_item_mini" *ngFor="let country of countries;"> 
     <span class="list_item_caption_mini" (click)="getCountry(country.id)">{{country.caption}}</span> 
     <div class="del_button" (click)="delCountry()"></div> 
     </div> 
    </form> 
    </fieldset> 

    <fieldset id="country_edit" *ngIf="visibility.countryE == 'active'" [@countryChangedE]="visibility.countryE"> 
    <form [formGroup]="countryEditForm" (submit)="countrySubmit();"> 
     <input class="form_control_mini" type="text" formControlName="id" hidden> 
     <input class="form_control_mini" type="text" placeholder="Caption" formControlName="caption"> 
     <input class="form_control_mini" type="text" placeholder="Language" formControlName="language"> 
     <div class="clearfix"></div> 
     <input type="submit" value="Ok" (click)="countrySubmit();"> 
     <input type="reset" value="New"> 
    </form> 
    </fieldset> 
</div> 

邏輯:我改變任何國家並關閉changeForm。在countrySubmit中,我需要調用getCountries()來刷新列表並使其更改,但是我的問題是getCountries在更改之前調用並且不起作用。

請描述如何正確執行此操作。如何刷新它? 或者我這樣做絕對錯誤? 感謝您的回答。

+0

我沒有看到你在'countrySubmit'中調用'getCountries()'。 – Pengyy

+0

是的,對不起,它是舊版本) – shmihshmih

回答

1

您可以使用switchMap在第一個結束後創建另一個Observable,請參閱documentation

this.literatureService.modCountry(this.countryEditForm.value) 
.switchMap(() => this.literatureService.getCountries('v_country.php')) 
.subscribe((country) => { 
    console.log(country); 
}); 
+0

感謝您的回答。我試圖用Observable switchMap來做,但是它讓我的應用程序變得更慢更困難。最後,我重新檢查了我的json並發現了錯誤。我選擇像這樣的決定: 'countrySubmit():無效{ this.literatureService.modCountry(this.countryEditForm.value) .catch(ERR => {返回ERR}) .subscribe(()=> { this.getCountries()}); this.visibility.countryE ='inactive'; this.visibility.countryL ='active'; }' – shmihshmih

相關問題