今天進行的部分,是整合Save/Load原本分散的(click)方法。
原本的程式碼是在父元件內呼叫子元件的地方指定調用名稱
<profile #myProfile [CHcard]="CHcard"></profile>
...
<characteristics #myCharacteristics [CHcard]="CHcard"></characteristics>
...
<skill-list #mySkillList [CHcard]="CHcard"></skill-list>
...
<backstory #myBackstory [CHcard]="CHcard"></backstory>
然後再分別呼叫子元件裡的方法,當初真的便宜行事,看著就很亂(汗)
// 儲存檔案
<button type="button" class="btn btn-primary"
(click)="saveAll()"
(click)="myProfile.saveProfileData()"
(click)="myCharacteristics.saveStatus()"
(click)="mySkillList.saveSkillData()"
(click)="myBackstory.saveBackstorys()">
Save
</button>
...
// 讀取檔案
<button type="submit" class="btn btn-primary d-flex mx-auto mt-3"
data-dismiss="modal" aria-label="Close"
(click)="loadJsonFile()"
(click)="myProfile.getProfileData()"
(click)="myCharacteristics.getStatus()"
(click)="mySkillList.getSkillData()"
(click)="myBackstory.getBackstorys()">
Load
</button>
修改成從父元件的ts檔案內用ViewChild讀入各子元件的資料,然後統一寫在getAll()與saveAll()裡面。
import { Component, ViewChild } from '@angular/core';
import { ProfileComponent } from
'../character/profile/profile.component';
import { CharacteristicsComponent } from
'../character/characteristics/characteristics.component';
import { SkillListComponent } from
'../character/skill-list/skill-list.component';
import { BackstoryComponent } from
'../character/otherdata/backstory.component';
@Component({
...
})
export class CharacterComponent {
@ViewChild(ProfileComponent, { static: false }) profile: ProfileComponent;
@ViewChild(CharacteristicsComponent, { static: false }) characteristics: CharacteristicsComponent;
@ViewChild(SkillListComponent, { static: false }) skillList: SkillListComponent;
@ViewChild(BackstoryComponent, { static: false }) backstory: BackstoryComponent;
...
saveAll() {
if (localStorage.getItem(this.CHcard) == null) {
let data = { "Charactor": this.CHcard };
localStorage.setItem(this.CHcard, JSON.stringify(data));
this.chCardBox.push(data["Charactor"]);
} else {
this.profile.saveProfileData();
this.characteristics.saveStatus();
this.skillList.saveSkillData();
this.backstory.saveBackstorys();
}
this.addNewCHcardData = "";
alert('所有資料已儲存');
}
getAll() {
let data = JSON.parse(localStorage.getItem(this.CHcard));
if (data.profiledata == undefined) {
alert("此資料卡內無資料");
} else {
this.profile.getProfileData();
this.characteristics.getStatus();
this.skillList.getSkillData();
this.backstory.getBackstorys();
}
}
}
整理過後的html就變得乾淨多了
// 儲存檔案
<button type="button" class="btn btn-primary"
(click)="saveAll()">
Save
</button>
...
// 讀取檔案
<button type="submit" class="btn btn-primary d-flex mx-auto mt-3"
data-dismiss="modal" aria-label="Close"
(click)="loadJsonFile()"
(click)="getAll()">
Load
</button>
另外其實還有個沒寫在之前list中,但已經被我偷偷改掉的bug......是statusSubData無法存檔的問題,這部分就只是沒有綁到[(ngModel)],所以才會「沒有反應,就是個html物件」。
= = = = =
你今天的努力
是否有跟未來的夢想
同一個等級?