如何在 Ionic 中正确读取 JSON 文件?

Posted

技术标签:

【中文标题】如何在 Ionic 中正确读取 JSON 文件?【英文标题】:How do I properly read a JSON file in Ionic? 【发布时间】:2021-12-16 07:34:33 【问题描述】:

我正在尝试使用 Ionic Angular 创建一个 DnD Character Builder 应用程序。我想将创建的字符保存到本地 JSON 文件中,以便于阅读和编辑。我创建了一个用于测试的硬编码 JSON 文件,但由于某种原因,我的代码似乎没有读取它。

编辑:我想通了。我需要做的就是将 ngOnInit 从 characters.service 直接移动到 tab1.ts。不需要中间人。希望这可以帮助那些与我做同样事情的人!

这里是 JSON 文件,characterList.json:

[
    
        "name": "Selena",
        "class": [
            "Sorcerer"
        ],
        "subclass": [
            "draconic"
        ],
        "levels": [
            1
        ],
        "totalLevel": 1,
        "race": "Human",
        "background": "Athlete",
        "maxHP": 8,
        "currentHP": 8,
        "temphp": 0,
        "hitDie": [
            6
        ],
        "hitDice": [
            1
        ],
        "stats": [
            14,
            12,
            12,
            11,
            10,
            16
        ],
        "statsShort": [
            2,
            1,
            1,
            0,
            0,
            3
        ],
        "savingThrows": [
            2,
            1,
            3,
            0,
            0,
            5
        ],
        "spellSlots": [
            2
        ],
        "currentSpellSlots": [
            2
        ],
        "pactMagicSpellLevel": 0,
        "pactMagicTotalSpellSlots": 0,
        "pactMagicCurrentSpellSlots": 0,
        "spellsKnown": [
            [
                "Firebolt",
                "Sword Burst",
                "Ray of Frost",
                "Prestidigitation",
                "Eldritch Blast"
            ],
            [
                "Burning Hands",
                "Chaos Bolt"
            ],
            [
                "Misty Step"
            ]
        ],
        "pactMagicSpellsKnown": [],
        "mainStat": 5,
        "customAttacks": [
            
                "name": "Sun Blade",
                "spell": false,
                "attBonus": "+6",
                "damage": "1d8 + 3",
                "range": "Melee",
                "stat": "Dex",
                "damageType": "fire"
            
        ],
        "gold": [
            0,
            0,
            0,
            10,
            0
        ],
        "statProficiencies": [
            "Athletics",
            "Acrobatics",
            "Insight",
            "Intimidation"
        ],
        "proficiencies": [
            "Dart",
            "Dagger",
            "Sling",
            "Quarterstaff",
            "Light Crossbow",
            "Land Vehicles"
        ],
        "proficiencyBonus": 2,
        "expertise": [],
        "alignment": "Lawful Good",
        "armorClass": 14,
        "speed": 30,
        "weapons": [
            "Quarterstaff",
            "Dagger"
        ],
        "armor": "",
        "shield": false,
        "languages": [
            "Common",
            "Undercommon",
            "Dwarven",
            "Draconic"
        ],
        "equipment": "Quarterstaff, Dagger, Dagger",
        "classFeatures": [
            "Sorcerer Features:"
        ],
        "feats": [
            "Spell Sniper"
        ],
        "featDescriptions": [
            "Feats:",
            "- Spell Sniper: The range on your ranged attack spells is doubled, you ignore 1/2 and 3/4 cover with ranged spell attacks, and you learn one cantrip."
        ],
        "subclassFeatures": [
            "Sorcerer Archetype: Draconic",
            " - You know Draconic and gain double your proficiency bonus on Charisma checks when speaking with dragons.",
            " - Gain 1 extra HP per level, and grow scales which have an AC of 13 when you aren't wearing armor."
        ],
        "raceFeatures": [
            "Human Features:",
            " - Athletics proficiency",
            " - Spell Sniper Feat"
        ],
        "backgroundFeatures": [
            "Athlete Features:",
            "There is a chance you can find people who have heard of your triumphs that will grant you shelter or information when in the general region from which you hail."
        ],
        "otherFeatures": "Text goes here",
        "personalityTraits": "Headstrong and focused",
        "ideals": "Victory at all costs",
        "bonds": "Whoever she considers to be her \"team\".",
        "flaws": "Has little mind for her own safety or that of those around her.",
        "backstory": "Idk I'm too tired to write this up rn",
        "notes": "This is a hard-coded character and I hate myself",
        "experience": 10
    ,
    
        "name": "Bodyguard",
        "class": [
            "Barbarian"
        ],
        "subclass": [
            "Zealot"
        ],
        "levels": [
            3
        ],
        "totalLevel": 3,
        "race": "Warforged",
        "background": "Knight",
        "maxHP": 45,
        "currentHP": 45,
        "tempHP": 0,
        "hitDie": [
            12
        ],
        "hitDice": [
            3
        ],
        "stats": [
            16,
            12,
            16,
            12,
            9,
            10
        ],
        "statsShort": [
            3,
            1,
            3,
            1,
            -1,
            0
        ],
        "savingThrows": [
            5,
            1,
            5,
            1,
            -1,
            0
        ],
        "spellSlots": [],
        "currentSpellSlots": [],
        "pactMagicSpellLevel": 0,
        "pactMagicTotalSpellSlots": 0,
        "pactMagicCurrentSpellSlots": 0,
        "spellsKnown": [],
        "pactMagicSpellsKnown": [],
        "mainStat": 0,
        "customAttacks": [
            
                "name": "Bone Breaker",
                "spell": false,
                "attBonus": "+7",
                "damage": "1d10 + 5",
                "range": "Melee",
                "stat": "Str",
                "damageType": "Bludgeoning"
            
        ],
        "gold": [
            0,
            0,
            0,
            10,
            0
        ],
        "statProficiencies": [
            "Athletics",
            "Arcana",
            "Perception",
            "Intimidation",
            "Persuasion"
        ],
        "proficiencies": [
            "Simple Weapons",
            "Martial Weapons",
            "Light Armor",
            "Medium Armor",
            "Shields",
            "Smith's tools",
            "Piano"
        ],
        "proficiencyBonus": 2,
        "expertise": [],
        "alignment": "Lawful Neutral",
        "armorClass": 15,
        "speed": 30,
        "weapons": [
            "Greatsword",
            "Javelin"
        ],
        "armor": "",
        "shield": false,
        "languages": [
            "Common",
            "Gnomish",
            "Infernal"
        ],
        "equipment": "Greatsword, Javelin (5), Explorer's pack, Set of traveler's clothes, Seal from your creator, coin pouch",
        "classFeatures": [
            "Barbarian Features:",
            "Rage: (3/3 per long rest)",
            " - You gain advantage on Strength checks and saving throws.",
            " - Deal +2 damage on strength based melee attacks.",
            " - Resistance vs bludgeoning, piercing, and slashing damage.",
            " - Lasts for 1 minute, as long as you deal or recieve damage every turn.",
            " - You cannot cast any spells while raging, if you are normally able to.",
            "Unarmored Defense: Add your Constitution modifier to Armor Class when not wearing armor.",
            "Reckless Attack: You can gain advantage on Strength based melee attacks for a turn, but all attack rolls have advantage on you until the start of your next turn.",
            "Danger Sense: You have advantage on Dexterity saving throws against things you can see coming."
        ],
        "feats": [],
        "featDescriptions": [],
        "subclassFeatures": [
            "Primal Path: Zealot",
            " - Your first weapon damage roll on your turn deals an extra 1d6 + [half barbarian level] radiant damage.",
            " - Any spell that would return you to life requires no material components."
        ],
        "raceFeatures": [
            "Warforged Features:",
            " - You are immune to disease, resist poison damage and have advantage against poison saving throws, and you don't need to sleep, breathe, eat, or drink.",
            " - Your long rests take 6 hours, during which you cannot move but are otherwise conscious.",
            " - Armor takes a part of your body, is impossible to remove against your will, and your AC is increased by 1."
        ],
        "backgroundFeatures": [],
        "otherFeatures": "Text goes here",
        "personalityTraits": "You are slow to anger but can be merciless and relentless once a situation has escalated to violence.",
        "ideals": "The Crown: Enemies of the church and king (or whatever ruler you follow) must be rooted out wherever they are found.",
        "bonds": "You owe all that you have to a noble lord or lady that sponsored your knighthood and now acts as your benefactor.",
        "flaws": "You are unshakable in the belief that you always have the higher moral ground.",
        "backstory": "Made by a wizard who died (sad!)",
        "notes": "This is a hard-coded character and I hate myself",
        "experience": 30
    
]

这里是读取 JSON 的文件,characters.service:

export class CharactersService implements OnInit 

  private characterJsonArray: Character[];

  constructor() 

  ngOnInit() 
    fetch('./assets/data/characterList.json').then( res => 
      res.json()).then(json => 
        this.characterJsonArray = json;
      );
    console.log(this.characterJsonArray[0].name);
    console.log(this.characterJsonArray[1].name);
  

  getAllCharacters(): Character[] 
    return this.characterJsonArray;
  

这是 tab1.ts,它将是显示字符列表的选项卡:

export class Tab1Page 

  public characters: any;

  constructor(public service: CharactersService,
    private router: Router
  )  

  ngOnInit(): void 
    this.characters = this.service.getAllCharacters();
  


最后是显示它们的 tab1.page.html 文件:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Characters
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">

  <ion-item-group>
    <ng-container *ngFor="let char of characters">
      <ion-item>
        <ion-label float:left> char.name </ion-label>
        <ion-text float:right> char.class[0] </ion-text>
      </ion-item>
    </ng-container>
  </ion-item-group>
  
</ion-content>

characters.service 中的 console.log 命令没有吐出任何内容,我什至不确定如何测试 JSON 文件是否被正确读取。

我真的被难住了,任何建议都会很重要。

【问题讨论】:

【参考方案1】:

您需要将服务更改为如下所示:

import  Injectable  from '@angular/core';
import  Observable  from 'rxjs';
import  HttpClient  from '@angular/common/http';
import  map  from 'rxjs/operators';

@Injectable(
  providedIn: 'root'
)
export class GetMenuService 

  constructor(private http: HttpClient)  

  getAllCharacters(): Observable<any> 
    console.log('getMenu1');
    return this.http.get('../../assets/data/characterList.json');
  

确保pathurl 正确,您可以从inspectNetwork 部分检查文件是否正确加载。

【讨论】:

以上是关于如何在 Ionic 中正确读取 JSON 文件?的主要内容,如果未能解决你的问题,请参考以下文章

Ionic 5:如何写入本地 JSON 文件?

如何遍历单个 JSON 文件以使每个对象出现在 Ionic 火种卡上?

如何仅使用 JavaScript 正确读取 json 文件 [重复]

离子读取本地 JSON 文件

ios的离子在哪里存储json文件?

每秒读取和更新json文件数据