簡體   English   中英

重用Angular組件無需使用switch語句即可加載不同的數據

[英]Reuse Angular component to load different data without using switch statement

我將我的應用程序從jquery移到了angular 5。

我有一個名為citySelect.Component.html的組件

在其中有3個選擇框-國家,省和城市

在我的城市中,選擇

citySelect.Component.html

  <select (change)="onCitySelect($event.target.value)">
                <option value="">--Select--</option>
                <option *ngFor="let c of cities" value={{c.id}}>
                    {{c.cityName}}
                </option>
            </select>

citySelect.Component.ts

onCitySelect(cityId: string) {
    if (cityId != "") {
        this.data.getCityPersons(cityId);
    }
}  

getCityPersonsdataService.ts中的一種方法,該方法將人員存儲在同一數據服務中的數組屬性中,該屬性允許該數組由另一個組件personForm.component使用。

dataService.ts

public persons: Person[];
public personsChange: Subject<Person[]> = new Subject<Person[] >();



getCityPersons(cityId: string) {
    this.loadCityPersons(cityId)
        .subscribe(success => {
            if (success) {
                this.personsChange.next(this.persons);
            }
        });
}

這一切都正確。 但是,我需要將citySelect.Component用於報告和其他形式。

我能想到的重用解決方案是可以將@Input傳遞給citySelect,然后基於在citySelect中具有if語句的示例。

citySelect.Component.ts

@Input() formName: string;
...
onCitySelect(cityId: string) {
    if (this.cityId != "") {
        switch(this.formName) { 
           case 'cityPatient': { 
              this.data.getCityPersons(cityId);
              break; 
           } 
           case 'cityReport1': { 
              this.data.fetchCityReport1(cityId);
              break; 
           } 
            case 'cityCityStats': { 
              this.data.fetchCityStats(cityId);
              break; 
           } 
        } 
    }
}  

上面的每個獲取組件都在數據服務中獲取不同的數組對象,這些對象又在不同的組件中被引用。

我如何修復代碼,以便使組件與知道要為組件重復使用以進行不同數據選擇的各個頁面獲取哪些數據更加隔離

使用jquery,我可以在各個頁面的citySelect上有一個事件,而無需使用switch語句就可以重用該組件。

最好的解決方案是不使用@Input而是@Output 您可以在用戶每次選擇一個人時調用輸出事件。

<app-city-select (personSelected)="getCityPersons($event)"></app-city-select>
<app-city-select (personSelected)="fetchCityReport($event)"></app-city-select>
<app-city-select (personSelected)="fetchCityStats($event)"></app-city-select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM