Product.JSON未在angular2应用程序中加载

时间:2018-02-05 12:18:09

标签: angular angular2-routing angular2-template angular2-forms

我在angular2应用程序中加载Product.json文件。

请在下面找到我的申请代码,建议

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { HttpModule } from '@angular/http';

@NgModule ({
   imports:      [ BrowserModule,HttpModule],
   declarations: [ AppComponent],
   bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { IProduct } from './product';
import { ProductService } from './products.service';
import { appService } from './app.service';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component ({
   selector: 'my-app',
   template: '<div>Hello</div>',
   providers: [ProductService]
})

export   class   AppComponent  {
   iproducts: IProduct[];
   constructor(private _product: ProductService) {
   }

   ngOnInit() : void {
      this._product.getproducts()
      .subscribe(iproducts => this.iproducts = iproducts);
   }
}

的index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Demoproject</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <my-app></my-app>
</body>
</html>

Products.json

[{
   "ProductID": 1,
   "ProductName": "ProductA"
},

{
   "ProductID": 2,
   "ProductName": "ProductB"
}]

products.service.ts

import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { IProduct } from './product';

@Injectable()
export class ProductService {
   private _producturl='app/products.json';
   constructor(private _http: Http){}

   getproducts(): Observable<IProduct[]> {
      return this._http.get(this._producturl)
      .map((response: Response) => <IProduct[]> response.json())
      .do(data => console.log(JSON.stringify(data)));
   }

}

product.ts

export interface IProduct {
   ProductID: number;
   ProductName: string;
}

它在控制台部分product.json文件中找不到错误(404)。

任何人请建议。我是angular2的新手

1 个答案:

答案 0 :(得分:1)

您需要export来自Products.json

的数据
export const productData : IProduct = [{
   "ProductID": 1,
   "ProductName": "ProductA"
},

{
   "ProductID": 2,
   "ProductName": "ProductB"
}]

OR

只需将该文件放在assets文件夹中即可访问。

有关详情: READ