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

时间:2018-06-01 14:19:54

标签: javascript json angular

在Angular任何版本(2,3,4,5)中需要帮助,我在过去2周内尝试过。任何帮助将不胜感激。

道歉,由于代码很大,我无法在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(数据将根据下拉内容进行更改)

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

metadata.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"
  }
]

app.config.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);
}

1 个答案:

答案 0 :(得分:1)

由于您无法分享演示,我自己展示了如何从API /本地json加载数据,您可以从这里试试。

请随意询问您是否不喜欢/我理解错误。

<强> DEMO

这里做了两件事,首先,从构造函数中获取元数据,这将在初始化应用程序时加载数据,然后在选项中选择单击方法以获取所选数据,然后该数据可以发送到URL到得到另一个数据。

我不知道你使用的css框架我在这里使用了角材料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;
  }

应用-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);
  }
}