【问题标题】:Undefined array in service Angular 5服务Angular 5中的未定义数组
【发布时间】:2018-04-04 15:38:34
【问题描述】:

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

path

应用模块

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 { }

帮助如何解决这个问题?

【问题讨论】:

  • 尝试返回 this.http.get("item.json").map(x => x.json());

标签: javascript html angular


【解决方案1】:

getdata() 必须将 get 方法返回的响应映射到 json 或 pojo 对象。添加 map() 方法可以做到这一点。参考以下代码sn -p:

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

【讨论】:

  • 也验证“item.json”的路径。如果文件在项目中,请提供类似“app/config/item.json”的路径
  • “试试这个”通常不是一个好的答案的标志。解释您更改的内容以及更改原因会得到更好的答案。见How to Answer
  • “Observable”类型上不存在属性“map”。
  • @АлександрСеробабов,编辑了答案。请参考更新
  • item.json 位于应用程序的根目录。
【解决方案2】:

Http 返回一个 Response,实际数据在它的 body 中。要访问它,请使用 .json() 方法,如下所示:

getData(){
        return this.http.get("./item.json").map(res => res.json());
    }

现在,无论您在哪里订阅这个,您都会得到您期望的对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2019-01-10
    • 2018-06-17
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多