Angular 2 中的 Http get 请求以从放置在资产中的 json 文件中获取数据 [英] Http get request in angular 2 to fetch data from a json file placed in assets

查看:23
本文介绍了Angular 2 中的 Http get 请求以从放置在资产中的 json 文件中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从放置在我的资产文件夹中的 json 文件中获取数据.我在我的应用程序中使用了角度材料.

我创建了一个帐户组件,其中包含 account.component.ts,account.component.html,account.component.scss,accountdetail.service.ts 文件.

我使用角材料的 ma​​t-select 组件实现了一个简单的下拉列表,我通过创建 filter.pipe.ts 文件为其应用了搜索过滤器.

下面是我的申请文件

app.module.ts

import { NgModule } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { BrowserModule };从@angular/platform-b​​rowser/animations"导入 { BrowserAnimationsModule };从'@angular/forms'导入{ReactiveFormsModule};从 './filter.pipe' 导入 { FilterPipe };从'@angular/forms'导入{FormsModule};从'@angular/http'导入{HttpModule};import { AppMaterialModule } from './app-material.module';import { AppRoutingModule } from './app-routing.module';从 './app.component' 导入 { AppComponent };从 './account/account.component' 导入 { AccountComponent };从 './account/accountdetail.service' 导入 { AccoundetailService };导入'./rxjs-operators';@NgModule({声明: [应用组件,帐户组件,过滤管],进口:[浏览器模块,应用路由模块,反应形式模块,浏览器动画模块,应用材料模块,表单模块,Http模块],提供者:[AcoundetailService],引导程序:[AppComponent]})导出类 AppModule { }

account.component.ts

import {Component, ViewChild, Inject, OnInit} from '@angular/core';从@angular/material"导入 {MatPaginator, MatTableDataSource};从'@angular/forms'导入{FormControl};从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/operator/startWith';导入 'rxjs/add/operator/map';从'@angular/forms'导入{ReactiveFormsModule};从@angular/forms"导入{FormGroup};从'./accountdetail.service'导入{ AccoundetailService};@成分({选择器:'应用程序帐户',templateUrl: './account.component.html',styleUrls: ['./account.component.scss'],提供者:[AccountetailService],})导出类 AccountComponent 实现 OnInit {过滤文本:字符串;部门 = [];构造函数(私人 _accdetailservice :AccountdetailService ){ }ngOnInit(){this._accdetailservice.accountdetails().subscribe(data => this.departments = data);}/* 表格从这里开始--------------- */displayColumns1 = ['accno', 'accdesc', 'investigator', 'accCPC','location','cdeptid','depdesc'];dataSource1= new MatTableDataSource(ELEMENT_DATA);@ViewChild(MatPaginator) 分页器:MatPaginator;ngAfterViewInit() {this.dataSource1.paginator = this.paginator;}}导出接口元素{acno: 号码;accdesc:字符串;调查员:字符串;accCPC:字符串;位置:字符串;cdeptid:编号;depdesc:字符串;}const ELEMENT_DATA: 元素 [] = [{accno: 5400343, accdesc: 'ASTRALIS LTD', 调查员:'Kruger, James G.', accCPC: 'OR',location:'ON',cdeptid: 110350,depdesc: 'Kruger Laboratory'},{accno: 5400344, accdesc: 'ASTRALIS LTD', 调查员:'Gelbard, Alyssa.', accCPC: 'OR',location:'ON',cdeptid: 110350,depdesc: 'Kruger Laboratory'}];

account.component.html

欢迎</mat-toolbar><br/><h3>部门</h3><br/><mat-form-field><mat-select style="min-width: 200px;"placeholder="要搜索的类型" [(value)]="dept"><input class="input1" matInput type="text" [(ngModel)]="filtertext"><mat-option *ngFor="let dep of Department | filter:filtertext >{{ 部门}}</mat-option></mat-select></mat-form-field><br/><br/><br/><!-- 表格从这里开始--><垫卡><div class="example-container mat-elevation-z8"><mat-table #table [dataSource]="dataSource1"><!-- 账号栏--><ng-container matColumnDef="accno"><mat-h​​eader-cell *matHeaderCellDef>帐号</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.accno}}</mat-cell></ng-容器><!-- 账户描述栏--><ng-container matColumnDef="accdesc"><mat-h​​eader-cell *matHeaderCellDef>账户描述 </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.accdesc}} </mat-cell></ng-容器><!-- 调查员栏--><ng-container matColumnDef="调查员"><mat-h​​eader-cell *matHeaderCellDef>调查员</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.investigator}} </mat-cell></ng-容器><!-- 帐户每次点击费用列 --><ng-container matColumnDef="accCPC"><mat-h​​eader-cell *matHeaderCellDef>帐户每次点击费用 </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.accCPC}}</mat-cell></ng-容器><!-- 位置列--><ng-container matColumnDef="location"><mat-h​​eader-cell *matHeaderCellDef>位置</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.location}}</mat-cell></ng-容器><!-- 客户部门 ID 列 --><ng-container matColumnDef="cdeptid"><mat-h​​eader-cell *matHeaderCellDef>ClientDeptID </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.cdeptid}}</mat-cell></ng-容器><!-- 部门描述栏--><ng-container matColumnDef="depdesc"><mat-h​​eader-cell *matHeaderCellDef>部门描述</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.depdesc}}</mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns1" ></mat-h​​eader-row><mat-row *matRowDef="让行;列:displayColumns1;"></mat-row></mat-table><mat-paginator #paginator[页面大小]="10"[pageSizeOptions]="[5, 10, 20]"></mat-paginator>

</mat-card>

accountdetail.service.ts

import { Injectable } from '@angular/core';从@angular/http"导入 { Http, Response };导入 'rxjs/add/operator/map';从@angular/router"导入 {RouterModule, Router};从 './account.component' 导入 { AccountComponent };@Injectable()导出类 AccountdetailService {构造函数(私有 _http:Http){}private _url="assets/accountdetails.json";帐户详细资料(){返回 this._http.get(this._url).map((response:Response)=>response.json());}}

我单独创建了 app-material.module.ts 来导入角度材质组件.

app-material.module.ts

import { NgModule } from '@angular/core';从'@angular/common'导入{CommonModule};进口 {垫工具栏模块,垫卡模块,垫输入模块,垫按钮模块,MatSidenav模块,MatIcon模块,垫扩展模块,MatPaginator 模块,垫表模块,匹配芯片模块,垫选择模块,MatTooltip 模块,MatCheckbox模块,MatGridList 模块,对话框模块来自'@angular/material';@NgModule({进口:[CommonModule],出口:[垫工具栏模块,垫卡模块,垫输入模块,垫按钮模块,MatSidenav模块,MatIcon模块,垫扩展模块,MatPaginator 模块,垫表模块,匹配芯片模块,垫选择模块,MatTooltip 模块,MatCheckbox模块,MatGridList 模块,对话框模块]})导出类 AppMaterialModule {}

app.component.ts

import { Component } from '@angular/core';@成分({选择器:'app-root',模板:`<router-outlet></router-outlet>`,})导出类 AppComponent {}

app-routing.module.ts

import { NgModule } from '@angular/core';从'@angular/router' 导入 { Routes, RouterModule };从 './account/account.component' 导入 { AccountComponent };const 路由:路由 = [{ path: 'account', 组件: AccountComponent},{ 路径:'**',重定向到:''}];@NgModule({进口:[RouterModule.forRoot(routes)],出口:[路由器模块]})导出类 AppRoutingModule { }

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';@管道({名称:'过滤器'})导出类 FilterPipe 实现 PipeTransform {变换(部门 1:任何,过滤文本:字符串){如果(过滤器文本===未定义){退货部门1;}否则如果(部门1){返回部门1.过滤器(功能(部门){return Department.value.toLowerCase().includes(filtertext.toLowerCase());}) } }}

当我编译并运行我的应用程序时,我收到如下所示的错误

任何人都可以帮我解决这个问题并为我的部门下拉列表实现获取请求.

解决方案

这是一个简单的错误.您可能应该仔细查看您的代码并进行故障排除,而不是直接询问 StackOverflow.您还应该缩短代码片段,以便我们可以立即追踪错误的来源.

<小时>

无论如何,这里的问题是你拼错了你的服务.在您的服务文件中,它被拼写为 AccountdetailService,但在您的模块文件中,它被导入为 AccountdetailService.这会导致问题.

app.module.ts:

import { AccountdetailService } from './account/accountdetail.service';//<- 这里@NgModule({//...提供者:[AccountdetailService]//...})导出类 AppModule {}

accountdetail.service.ts:

@Injectable()导出类 AccountdetailService {//...}

<小时>

顺便说一下,您应该将您的服务重命名为 AccountDetailService 因为account"和detail"是两个不同的词,而detail"这个词应该以大写字母D"开头.这将遵循 PascalCase 语法.

I am trying to fetch data from a json file placed in my assets folder.I am using angular material in my application.

I have created a account component which has account.component.ts,account.component.html,account.component.scss,accountdetail.service.ts files.

I have implemented a simple dropdown using mat-select component of angular material for which i applied search filter by creating filter.pipe.ts file.

Below shown are my application files

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { FilterPipe } from './filter.pipe';
import { FormsModule } from '@angular/forms';
import { HttpModule} from '@angular/http';

import { AppMaterialModule } from './app-material.module';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AccountComponent } from './account/account.component';

import { AccoundetailService } from './account/accountdetail.service';



import './rxjs-operators';


@NgModule({
  declarations: [
    AppComponent,
    AccountComponent ,
    FilterPipe      
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    AppMaterialModule,
    FormsModule ,
    HttpModule   
  ],
  providers: [AccoundetailService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

account.component.ts

import {Component, ViewChild, Inject, OnInit} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup } from '@angular/forms';

import { AccoundetailService } from './accountdetail.service';



@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss'],

  providers: [AccoundetailService],
})


export class AccountComponent implements OnInit {

 filtertext:string;
 departments = [];


constructor(private _accdetailservice :AccountdetailService ) { }

ngOnInit(){
  this._accdetailservice.accountdetails()
  .subscribe(data => this.departments = data);
}




  /* Table Starts here
  ---------------------- */
 displayedColumns1 = ['accno', 'accdesc', 'investigator', 'accCPC','location','cdeptid','depdesc'];
  dataSource1= new MatTableDataSource<Element>(ELEMENT_DATA);


  @ViewChild(MatPaginator) paginator: MatPaginator;

   ngAfterViewInit() {
    this.dataSource1.paginator = this.paginator;
  }
}

export interface Element {
  accno: number;
  accdesc: string;
  investigator: string;
  accCPC: string;
  location:string;
  cdeptid: number;
  depdesc: string;
}

const ELEMENT_DATA: Element[] = [
  {accno: 5400343, accdesc: 'ASTRALIS LTD', investigator:'Kruger, James G.', accCPC: 'OR',location:'ON',cdeptid: 110350,depdesc: 'Kruger Laboratory'},

  {accno: 5400344, accdesc: 'ASTRALIS LTD', investigator:'Gelbard, Alyssa.', accCPC: 'OR',location:'ON',cdeptid: 110350,depdesc: 'Kruger Laboratory'}

];

account.component.html

<mat-toolbar color="primary" style="width:100%"> WELCOME </mat-toolbar><br/>

<h3>Department</h3><br/>

            <mat-form-field>
                      <mat-select style="min-width: 200px;" placeholder="Type to search"  [(value)]="dept">
                      <input class="input1" matInput type="text" [(ngModel)]="filtertext">
                        <mat-option *ngFor="let dep of departments  | filter:filtertext >
                          {{ dep.department }}
                        </mat-option>
                      </mat-select>
                    </mat-form-field>

<br/> <br/> <br/> 




<!-- Table starts here -->

<mat-card>
<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource1">

    <!-- Account No. Column -->
    <ng-container matColumnDef="accno">
      <mat-header-cell *matHeaderCellDef> Account No. </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.accno}}</mat-cell>
    </ng-container>

    <!-- Account Description Column -->
    <ng-container matColumnDef="accdesc">
      <mat-header-cell *matHeaderCellDef> Account Description </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.accdesc}} </mat-cell>
    </ng-container>

    <!-- Investigator Column -->
    <ng-container matColumnDef="investigator">
      <mat-header-cell *matHeaderCellDef> Investigator </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.investigator}} </mat-cell>
    </ng-container>

    <!-- Account CPC Column -->
    <ng-container matColumnDef="accCPC">
      <mat-header-cell *matHeaderCellDef> Account CPC </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.accCPC}}</mat-cell>
    </ng-container>

     <!-- Location Column -->
    <ng-container matColumnDef="location">
      <mat-header-cell *matHeaderCellDef> Location </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.location}}</mat-cell>
       </ng-container>


     <!-- Client Dept ID Column -->
    <ng-container matColumnDef="cdeptid">
      <mat-header-cell *matHeaderCellDef> ClientDeptID </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.cdeptid}}</mat-cell>
       </ng-container>


    <!-- Dept Description Column -->
    <ng-container matColumnDef="depdesc">
      <mat-header-cell *matHeaderCellDef> Dept Description  </mat-header-cell>
      <mat-cell *matCellDef="let element">{{element.depdesc}}</mat-cell>
       </ng-container>


    <mat-header-row *matHeaderRowDef="displayedColumns1" ></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns1;"></mat-row>
  </mat-table>

  <mat-paginator #paginator
                 [pageSize]="10"
                 [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</div>
</mat-card>

accountdetail.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import {RouterModule, Router} from '@angular/router';
import { AccountComponent } from './account.component';


@Injectable()
export class AccountdetailService {

  constructor(private _http:Http ) { }

  private _url="assets/accountdetails.json";

  accountdetails(){
  return this._http.get(this._url)
    .map((response:Response)=>response.json());
  }

}

I have separately created app-material.module.ts to import the angular material components.

app-material.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
  MatToolbarModule,
  MatCardModule,
  MatInputModule,
  MatButtonModule,
  MatSidenavModule,
  MatIconModule,
  MatExpansionModule,
  MatPaginatorModule,
  MatTableModule,
  MatChipsModule,
  MatSelectModule,
  MatTooltipModule,
  MatCheckboxModule,
  MatGridListModule,
  MatDialogModule
} from '@angular/material';

@NgModule({
  imports: [CommonModule],
  exports: [
  MatToolbarModule,
  MatCardModule,
  MatInputModule,
  MatButtonModule,
  MatSidenavModule,
  MatIconModule,
  MatExpansionModule,
  MatPaginatorModule,
  MatTableModule,
  MatChipsModule,
  MatSelectModule,
  MatTooltipModule,
  MatCheckboxModule,
  MatGridListModule,
  MatDialogModule
   ]
})
export class AppMaterialModule {}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<router-outlet></router-outlet> `,
  })

export class AppComponent {}

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AccountComponent } from './account/account.component';

const routes: Routes = [
  { path: 'account', component: AccountComponent},
  { path: '**', redirectTo: ''}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(departments1: any, filtertext: string) {
    if(filtertext=== undefined){
    return departments1;
    } else if(departments1)
    {
         return departments1.filter(function(department){
         return department.value.toLowerCase().includes(filtertext.toLowerCase());

         }) } }}

when I compile and run my application I am getting the error as shown below

can anybody please help me to resolve this issue and implement the get request for my department dropdown.

解决方案

It's a simple error. You should probably look closely at your code and troubleshoot instead of straight away asking on StackOverflow. You should also shorten your code snippets so that we can straight away trace where the error came from.


Anyways, the problem here is that you spelt your service wrongly. In your service file, it was spelt as AccountdetailService, but in your module file, it was imported as AccoundetailService. This causes the problem.

app.module.ts:

import { AccountdetailService } from './account/accountdetail.service'; // <- Over here

@NgModule({
  // ...
  providers: [AccountdetailService]
  // ...
})
export class AppModule {}

accountdetail.service.ts:

@Injectable()
export class AccountdetailService {
  // ...
}


By the way, you should rename your service to AccountDetailService since "account" and "detail" are two different words altogether and the word "detail" should start with a capital letter "D" instead. This will follow the PascalCase syntax.

这篇关于Angular 2 中的 Http get 请求以从放置在资产中的 json 文件中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆