首页 > 解决方案 > 写入 JSON 文件并在 Angular 中的组件上显示相同的内容

问题描述

具有 4 个组件的项目 1. 登录 2. 主页(查看员工的详细信息) 3. 查看(显示员工的完整详细信息)和 4. 编辑。我已经能够从 .json 文件中读取员工详细信息并显示在详细视图组件和视图组件上。

现在我想更改 JSON 文件中可用的详细信息并在 View 和 ViewinDetail 组件上显示相同的内容。

我的 Employee.json 如下:

[
    {
        "id": 1,
        "firstName": "Abhi",
        "lastName": "A B",
        "gender": "male",
        "age": 25,
        "email": "Abhi@gmail.com",
        "phoneNumber": 8888888888,
        "department": "IT",
        "address": "Bengaluru"
    },
    {
        "id": 2,
        "firstName": "Amogh",
        "lastName": "A M",
        "gender": "male",
        "age": 25,
        "email": "Amogh@gmail.com",
        "phoneNumber": 8888888888,
        "department": "IT",
        "address": "Bengaluru"
    },
    {
        "id": 3,
        "firstName": "Harsha",
        "lastName": "H A",
        "gender": "male",
        "age": 25,
        "email": "Harsha@gmail.com",
        "phoneNumber": 8888888888,
        "department": "IT",
        "address": "Bengaluru"
    }
]

我的 home.html 如下:

<header>Welcome Home</header>
<br />
<div class="container panel panel-default" *ngFor="let employee of employeeList;">
        <div class="panel-heading">
                <h3 class="panel-title">{{employee.firstName}} {{employee.lastName}}</h3>
        </div>
        <div class="panel-body">
                <div class="col-xs-10">
                        <div class="row vertical-align">
                                <div class="col-xs-8 offset-md-2">
                                        <div class="row">
                                                <div class="col-xs-6">
                                                        First Name
                                                </div>
                                                <div class="col-xs-6">
                                                        : {{employee.firstName}}
                                                </div>
                                        </div>
                                        <div class="row">
                                                <div class="col-xs-6">
                                                        Last Name
                                                </div>
                                                <div class="col-xs-6">
                                                        : {{employee.lastName}}
                                                </div>
                                        </div>
                                        <div class="row">
                                                <div class="col-xs-6">
                                                        Gender
                                                </div>
                                                <div class="col-xs-6">
                                                        : {{employee.gender}}
                                                </div>
                                        </div>
                                        <div class="row">
                                                <div class="col-xs-6">
                                                        Department
                                                </div>
                                                <div class="col-xs-6">
                                                        : {{employee.department}}
                                                </div>
                                        </div>
                                        <div>
                                                <button class="btn btn-primary" (click)="viewEmployee(employee.id)">
                                                        View</button>&nbsp;
                                                <button class="btn btn-primary" (click)="editEmployee(employee.id)">
                                                        Edit
                                                </button>
                                        </div>
                                </div>
                        </div>
                </div>
        </div>
</div>

我的 home.ts 如下:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import employees from '../employeeDetails/employees.json';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  constructor(private router: Router) { }
  public employeeList: {
    id: number;
    firstName: string;
    lastName: string;
    gender: string;
    age: number;
    email?: string;
    phoneNumber?: number;
    department: string;
  }[] = employees;
  // tslint:disable-next-line: use-lifecycle-interface
  ngOnInit(): void { }

  viewEmployee(id): any {
    this.router.navigateByUrl(`/view/${id}`);
  }

  editEmployee(i): any {
    this.router.navigateByUrl('/edit');
  }
}

我的 view.html 如下:

<header>View Page</header>
<br />
<div class="container panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">{{employee.firstName}} {{employee.lastName}}</h3>
  </div>
  <div class="panel-body">
    <div class="col-xs-10">
      <div class="row vertical-align">
        <div class="col-xs-8 offset-md-2">
          <div class="row">
            <div class="col-xs-6">
              First Name
            </div>
            <div class="col-xs-6">
              : {{employee.firstName}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Last Name
            </div>
            <div class="col-xs-6">
              : {{employee.lastName}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Gender
            </div>
            <div class="col-xs-6">
              : {{employee.gender}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Age
            </div>
            <div class="col-xs-6">
              : {{employee.age}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Email
            </div>
            <div class="col-xs-6">
              : {{employee.email}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Phone Number
            </div>
            <div class="col-xs-6">
              : {{employee.phoneNumber}}
            </div>
          </div>
          <div class="row">
            <div class="col-xs-6">
              Department
            </div>
            <div class="col-xs-6">
              : {{employee.department}}
            </div>
          </div>
          <div>
            <button class="btn btn-primary" (click)="editEmployee()">
              Edit
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

我的view.ts如下:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import employees from '../employeeDetails/employees.json';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
  constructor(private router: Router, private route: ActivatedRoute) { }
  public employeeList: {
    id: number;
    firstName: string;
    lastName: string;
    gender: string;
    age: number;
    email?: string;
    phoneNumber?: number;
    department: string;
  }[] = employees;
  employee;
  ngOnInit(): void {
    this.route.params.subscribe((params) => {
      const employeeId = params.id;
      this.employee = employees.filter((e) => e.id === +employeeId)[0];
    });
  }
  editEmployee(): any {
    this.router.navigateByUrl('/edit');
  }
}

我的edit.html如下:

<header>Edit Page</header>
<div class="container" style="margin-top:1%" action="/view">
    <div class="col-md-6 col-md-offset-3">
        <div class="form-group">
            <label for="exampleInputEmail">First Name</label>
            <input type="text" class="form-control">
        </div>
        <div class="form-group">
            <label for="exampleInputPassword">LastName</label>
            <input type="text" class="form-control">
        </div>
        <div class="form-group">

            <tr><label for="exampleInputGender">Gender : </label>
                &nbsp;&nbsp;<td><input type="radio" id="male" name="gender" value="male" checked="checked">
                    <label for="male">Male</label><br></td> &nbsp;&nbsp;
                <td><input type="radio" id="female" name="gender" value="female">
                    <label for="female">Female</label></td>
            </tr>


        </div>
        <div class="form-group">
            <label for="exampleInputAge">Age</label>
            <input type="number" class="form-control">
        </div>
        <div class="form-group">
            <label for="exampleInputEmail">Email</label>
            <input type="email" class="form-control">
        </div>
        <div class="form-group">
            <label for="exampleInputPhoneNumber">Phone Number</label>
            <input type="text" class="form-control" id="exampleInputPhoneNumber">
        </div>
        <div class="form-group">
            <label for="exampleInputPhoneNumber">Address</label>
            <textarea type="textbox" class="form-control" id="exampleInputAddress"></textarea>
        </div>
        <input type="submit" value="Submit" (click)=editDetails()>
    </div>
</div>

我的edit.ts如下:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import employees from '../employeeDetails/employees.json';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  constructor(private router: Router, private route: ActivatedRoute) { }
  public employeeList: {
    id: number;
    firstName: string;
    lastName: string;
    gender: string;
    age: number;
    email?: string;
    phoneNumber?: number;
    department: string;
  }[] = employees;

  ngOnInit(): void {
  }
  editDetails(): any {
    this.router.navigateByUrl('/edit');
  }
}

请帮忙,我不太清楚如何进行。我想编辑 .json 文件,但不知道该怎么做。任何其他方法也是可以接受的。

标签: javascripthtmljsonangulartypescript

解决方案


您不能仅通过打字稿写入存储在项目中的 JSON 文件。

我假设您想要复制服务器,这就是您在json本地存储并获取组件中的值的原因。

要写入这样的 JSON 文件,您需要安装类似json-server 的东西,然后POST调用 localhost 服务器。这应该会给你预期的行为。

要获取json数据,您需要GET调用同一localhost台服务器


正如评论中提到的,如果你想使用sesssionStorage,你可以简单地将 json 保存到ParentComponentas

constructor(){
  sessionStorage.setItem('empList',employees);
}

然后使用它OtherComponents,你可以这样做:

ngOnInit(){
  const data = JSON.parse(sessionStorage.getItem('empList'));
  if (!!data){
     // there is no data in sessionStorage
  }
}

推荐阅读