【问题标题】:Angular 2+, on drop-down change read value and load data - json filesAngular 2+,下拉更改读取值并加载数据-json文件
【发布时间】:2018-06-01 14:19:53
【问题描述】:

在 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);
}

【问题讨论】:

    标签: javascript json angular


    【解决方案1】:

    由于您无法分享演示,我制作了自己的演示以展示如何从 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);
      }
    }
    

    【讨论】:

    • 感谢您的回答。只是我想知道的几件事。 1. 我的下拉菜单和仪表板位于不同的组件中。我想从 navigation.component 获取 {{meta}} 值到dashboard.component。 2. 初始加载我需要加载值(不仅仅是下拉列表)。你能帮我吗,
    • 如果我做对了,那么您需要从路由器传递值并接收该值,然后调用一项服务来获得您所需要的。
    • 任何参考(jsfiddle,plunker)请
    • 非常感谢,让我查一下。我看到一个问题初始数据未更新。我想在启动时显示下拉值和帖子。这可能吗?
    • 是的,您需要一项服务来做到这一点,或者 @Input / @Output 将数据从父级传递给子级,反之亦然。你可以看到我在这里使用 app-config 作为服务来保存数据。
    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2014-01-10
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多