javascript - Angular 2+,下拉更改读取值和加载数据 - json 文件

标签 javascript json angular

在 Angular 任何版本(2、3、4、5)中需要一点帮助,我从过去两周开始尝试。任何帮助将不胜感激。

抱歉,由于代码太大,我无法将其添加到 Plunker 或 JSfiddle 中。

我的工作流程是这样的

1 - 加载 metadata.json

2 - 从 metadata.json 中读取第一个值

3 - 从 APP_INITIALIZER

中的文件夹加载第一个 json

4 - 在下拉列表中填充 metadata.json 中的所有值

5 - 每当下拉值更改时加载相关的 json 并在 UI 中显示对象

我有 3 个组件

  • Navigation.component(下拉变化在这里触发)

  • dashboard.component(数据会根据下拉内容变化)

  • programmer.component(数据会根据下拉内容改变)

每当触发 Dropdown 更改事件时,我想从 json 加载数据。

元数据.json

[
  {
    "name": "Q_1090",
    "value": "project_q_1090.json"
  },
  {
    "name": "Q_1234",
    "value": "project_q_1234.json"
  },
  {
    "name": "Q_1528",
    "value": "project_q_1528.json"
  }
]

应用程序配置.ts

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AppConfig {
    config: any;
    user: any;
    objects: any;
    fileName: any;
    constructor(private http: Http) {
        console.log('ConfigService called.')
    }

    load(projectName) {
        return new Promise((resolve) => {

            /** This method: Loads "host_configuration.json" to get the current working environment. */
            this.http.get('./assets/host_configuration.json').map(res => res.json())
                .subscribe(config => {
                    console.log('Configuration loaded');
                    this.config = config;

                    /** This method: Loads all the objects from json */
                    let getSummaryParameters: any = null;
                    getSummaryParameters = this.http.get('./assets/json/' + projectName);

                    if (getSummaryParameters) {
                        getSummaryParameters
                            .map(res => res.json())
                            .subscribe((response) => {
                                this.objects = response;
                                return resolve(true);
                            });
                    } else {
                        return resolve(true);
                    }
                });
        });
    }

    loadMetadata() {
        return new Promise((resolve) => {
        //reading metadata.json
            this.http.get('./assets/metadata.json').map(res => res.json())
                .subscribe(fileName => {
                    console.log('metadata loaded');
                    this.fileName = fileName;
                    return resolve(true);
                });
        });
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule, JsonpModule } from '@angular/http';

import { AppRoutes } from './app.routing';
import { AppConfig } from './app.config';

import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { SharedModule } from './shared/shared.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BreadcrumbsComponent } from './navigation/breadcrumbs/breadcrumbs.component';
import { TitleComponent } from './navigation/title/title.component';


@NgModule({
    declarations: [
        AppComponent,
        NavigationComponent,
        BreadcrumbsComponent,
        TitleComponent

    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        RouterModule.forRoot(AppRoutes),
        SharedModule,
        HttpClientModule,
        HttpModule,
        JsonpModule,
        FormsModule

    ],
    providers: [AppConfig,
        {
            provide: APP_INITIALIZER,
            useFactory: (config: AppConfig) => () => config.load('project_q_1234.json'),
            deps: [AppConfig],
            multi: true
        }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { AppConfig } from '../../app.config';

declare var Chart;

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: [
        './dashboard.component.css'
    ]
})

export class DashboardComponent implements OnInit {

    constructor(public appConfig: AppConfig, private hostConfig: AppConfig, public getSummaryParameters: AppConfig) { }

    ngOnInit() {
        this.updates();
    }

    updates() {

        //assign all Parameters to objects
        this.objects = this.getSummaryParameters.objects;

        var JsonData = this.objects.Information.data;
        console.log(JsonData["0"]["0"] + " : " + JsonData["0"][1]);
    }
}

programmer.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Chart } from 'chart.js';
import { CommonModule } from '@angular/common';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { AppConfig } from '../../app.config';
declare function ChangeSortOrder(): any;

@Component({
    selector: 'app-simple-page',
    templateUrl: './programmer.component.html'
})

export class ProgrammerComponent implements OnInit {
    objects;

    constructor(public appConfig: AppConfig, private hostConfig: AppConfig, public getSummaryParameters: AppConfig, private modalService: NgbModal) { }

    ngOnInit() {
        this.updateData();
    }
    updateData() {

        //assign all Parameters to objects
        this.objects = this.getSummaryParameters.objects;

    }

}

navigation.component.ts

import { Component, ElementRef, OnInit, ViewChild, Injectable, NgModule } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { AppConfig } from '../app.config';
import { DashboardComponent } from '.././pages/dashboard/dashboard.component';
import { ProgrammerComponent } from '.././pages/programmer/programmer.component';


@Component({
  selector: 'app-admin',
  templateUrl: './navigation.component.html',
  providers: [DashboardComponent, ProgrammerComponent]
})

@Injectable()
export class NavigationComponent implements OnInit {

  fileName: any;
  selectedfileName: any;
  config: any;
  objects: any;



  constructor(public menuItems: MenuItems, private http: Http, private appConfig: AppConfig, public router: Router,
    private hostConfig: AppConfig, public getSummaryParameters: AppConfig, private dashboardComponent: DashboardComponent,
    private programmerComponent: ProgrammerComponent) {

  }

  ngOnInit() {
    this.appConfig.loadMetadata().then(fileName => {
      this.fileName = this.appConfig.fileName;

      //Initial loading for project Drop-down, Fetch first JSON from metadata.json
      this.selectedfileName = 'project_q_1234.json';
    });

  }

  refreshApp(projectName) {
    this.appConfig.load(projectName).then(objects => {
      this.objects = objects;
      this.updateData();

     //this commented code partially works but data is not loading properlly
      //this.dashboardComponent.updates();
      //this.programmerComponent.updateData();
      //this.qCProgrammerComponent.updateQCData();
    });
  }

  updateData() {
    console.log("Dropdown change start");
    //load all the host related settings
    this.config = this.hostConfig.config;
    localStorage.setItem('url', this.config.host);
    localStorage.setItem('folder', this.config.folder);
}

最佳答案

由于您无法共享演示,我制作了自己的演示来展示如何从 API/本地 json 加载数据,您可以从此处尝试。

如果这不是您想要的场景,请随意询问/我理解错误。

DEMO

这里完成了两件事,首先,从构造函数中获取元数据,它将在初始化您的应用程序时加载您的数据,其次在选项中选择一个点击方法以获取所选数据,然后该数据可以发送到 url 到获取另一个数据。

我不知道你用的是哪个css框架我这里用的是angular material 2.

app.component.html

<p>
    Using jsonplaceholder.typicode.com API
</p>
<mat-form-field style="width: 100%">
    <mat-select placeholder="Select Any Users" [(value)]="selectedUser">
        <mat-option *ngFor="let meta of metadata" (click)="getInfoAboutIndividualMeta(meta)" [value]="meta.name">
            {{ meta.name }}
        </mat-option>
    </mat-select>
</mat-form-field>

<mat-form-field style="width: 100%" *ngIf="selectedUser">
    <mat-select placeholder="Select Posts from {{selectedUser}}">
        <mat-option *ngFor="let post of posts" (click)="selectedPost(post)" [value]="post.title">
            {{ post.title }}
        </mat-option>
    </mat-select>
</mat-form-field>


<mat-card *ngIf="selectPost">
    <h1>{{selectPost?.title}}</h1>
    <p [innerHTML]="selectPost?.body"></p>
</mat-card>

app.component.ts

    name = 'Angular 6';
  metadata: any[];
  posts: any[];
  selectedUser: string;
  selectPost: Object;
  constructor(private appConfig: AppConfig) {
    this.metadata = [];
    this.posts = [];
    this.initialize();
  }

  initialize() {
    this.appConfig.getMetadataJSON().subscribe(res => {
      this.metadata = res;
      this.selectedUser = this.metadata[0].name;
    });
  }

  getInfoAboutIndividualMeta(meta: Object) {
    console.log(meta);
    const userId = meta.id;
    this.appConfig.getIndividualMetadataJSON(userId).subscribe( res => {
      this.posts = res;
    });
  }

  selectedPost(post: Object) {
    this.selectPost = post;
  }

app-config.class.ts

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs';

@Injectable()
export class AppConfig {

  constructor(private httpClient: HttpClient) {

  }

  public getMetadataJSON(): Observable<any> {
    // Due to stackblitz can't get the local access I put this value to another api source
    // const apiUrl = './assets/metadata.json'; // You can use this as well
    const apiUrl = 'https://jsonplaceholder.typicode.com/users';
    return this.httpClient.get(apiUrl);
  }

  public getIndividualMetadataJSON(userId: number): Observable<any> {
    const apiUrl = 'https://jsonplaceholder.typicode.com/posts?userId=' + userId;
    return this.httpClient.get(apiUrl);
  }
}

关于javascript - Angular 2+,下拉更改读取值和加载数据 - json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50645515/

相关文章:

javascript - Socket.IO 在 Express 4 路由上发出

javascript - 尝试将视听器转换为代码笔未成功……需要劝告

javascript - 在更大的屏幕尺寸下消失的导航

node.js - 在 Angular 应用程序中,我不断收到此错误 Cannot find module 'fs'

dart - 在 angular2 中设置自定义 bool 属性的正确语法是什么

javascript - 在 Angular 中将 Promise 从一个服务调用传递到另一个服务调用

javascript - 访问 json 数据时出现问题

json - 将 JSON 对象转换为 URL 查询字符串的命令行

json - 在Skype中获取dialogflow V2的轮播列表

angular - 没有 FormBuilder 的提供者