[英]Undefined array in service Angular 5
我this.http.get("item.json");
有this.http.get("item.json");
初始化返回一個空數組。該數組的DataService
服務已滿。
我正在使用Angular 5
{
"name": "stock",
"version": "1.0.0",
"description": "Angular 5",
"scripts": {
"dev": "webpack-dev-server --hot --open",
"build": "webpack"
},
"dependencies": {
"@angular/common": "~5.0.0",
"@angular/compiler": "~5.0.0",
"@angular/core": "~5.0.0",
"@angular/forms": "~5.0.0",
"@angular/platform-browser": "~5.0.0",
"@angular/platform-browser-dynamic": "~5.0.0",
"@angular/router": "~5.0.0",
"core-js": "^2.4.1",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},
"devDependencies": {
"@types/node": "^8.0.47",
"typescript": "^2.6.0",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1",
"angular2-template-loader": "^0.6.2",
"awesome-typescript-loader": "^3.3.0",
"uglifyjs-webpack-plugin": "^1.0.1",
"raw-loader": "^0.5.1",
"html-loader": "^0.5.1"
}
}
服務HttpService文件請求:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HttpService{
constructor(private http: HttpClient) {}
getData(){
return this.http.get("item.json");
}
}
在DataService服務中獲取數據以進行商品管理
import {Item} from './item';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {HttpService} from './http.service';
import {Injectable} from '@angular/core';
@Injectable()
export class DataService{
private gItem: Item[];
constructor(private http: HttpService){
this.http.getData().subscribe((data: Item[]) => this.gItem = data["Stock"]);
console.log("constructor " + this.gItem);
}
getData(): Item[] {
console.log("getData()" + this.gItem);
return this.gItem;
}
addData(text: string, price: number) {
console.log(this.gItem);
if(text==null || text==undefined || text.trim()=="")
return;
if(price==null || price==undefined)
return;
this.gItem.push(new Item(text, price));
}
delete(item: Item): void {
const index: number = this.gItem.indexOf(item);
if(index !== -1) {
this.gItem.splice(index, 1)
}
}
}
在現場存儲組件上打印
import { Component, OnInit} from '@angular/core';
import { HttpClient} from '@angular/common/http';
import {DataService} from './data.service'
import {Item} from './item';
import { NgForm} from '@angular/forms'
import { HttpService} from './http.service'
import {Injectable} from '@angular/core';
@Component({
selector: 'home-app',
template: `<div class="page-header">
<h1> Список покупок </h1>
</div>
<div class="panel">
<div class="form-inline">
<div class="form-group">
<div class="col-md-8">
<input class="form-control" [(ngModel)]="text" placeholder = "Название" />
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="number" class="form-control" [(ngModel)]="price" placeholder="Цена" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<button class="btn btn-default" (click)="addItem(text, price)">Добавить</button>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Предмет</th>
<th>Цена</th>
<th>Куплено</th>
<th>Удалить</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td>{{item.purchase}}</td>
<td>{{item.price}}</td>
<td><input type="checkbox" [(ngModel)]="item.done" /></td>
<td nowrap=nowrap><button (click)="delete(item)"><i class="icon-minus--sign"></i></button></td>
</tr>
</tbody>
</table>
</div>`,
providers: [DataService, HttpService],
})
export class HomeComponent implements OnInit {
items: Item[];
constructor(private dataService: DataService){}
// инициализируем компонент
ngOnInit(){
this.items = this.dataService.getData();
}
// метод добавления привязанная к кнопке
addItem(text: string, price: number): void {
this.dataService.addData(text, price);
}
// метод удаления
delete(item: Item): void {
this.dataService.delete(item);
}
}
appModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
// пути по компонентам
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
// пути
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { Item } from './item';
import {DataService} from './data.service';
import {HttpService} from './http.service';
//функциональность декоратора NgModule, без которой мы не сможем создать модуль
@NgModule({
// другие модули
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpClientModule
],
//классы представлений
declarations: [ AppComponent, routingComponents],
// корневой компонент
bootstrap: [ AppComponent ]
})
export class AppModule { }
幫助如何解決這個問題?
getdata()必須將get方法返回的響應映射到json或pojo對象。 添加map()方法可以做到這一點。 請參考以下代碼段:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HttpService{
constructor(private http: HttpClient) {}
getData(){
return this.http.get("./item.json");
}
}
Http返回一個Response,實際數據在它的主體中。 要使用它,請使用.json()方法,如下所示:
getData(){ return this.http.get("./item.json").map(res => res.json()); }
現在,無論您在哪里訂閱,都將獲得您所期望的對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.