(Angular2)JSON数据(http.get())未定义,数据未在组件

时间:2017-07-13 19:52:54

标签: javascript json angular typescript asynchronous

我的http-data.service接受组件模板中的输出json。最初,控制台显示前几个调用未定义,并且以下调用已经采用json,但是如果检查组件,则组件显示将数据输出到组件的方法仅被调用一次,由于数据尚未到达,因此写入未定义,但在json到达后未更新。请帮忙理解为什么?谢谢

我的http-data.service

            import {Injectable} from '@angular/core';
            import {Http} from '@angular/http';
            import {Response} from '@angular/http';
            import {Observable} from 'rxjs/Observable';
            import 'rxjs/add/operator/map';

            @Injectable()
            export class HttpService{
                constructor(private http: Http) {}

                getDataOrganizations(): Observable<any[]>{
                    return this.http.get('http://localhost:3010/data')
                        .map((resp:Response)=>{
                            let dataOrganizations = resp.json().organization;
                            return dataOrganizations;
                        });
                }

                getDataModules(): Observable<any[]> {       
                    return this.http.get('http://localhost:3010/data')
                        .map((resp: Response)=> {
                            let dataModules = resp.json().modules;
                            return dataModules;
                        });
                }

                getDataPresets(): Observable<any[]> {       
                    return this.http.get('http://localhost:3010/data')
                        .map((resp: Response)=> {
                            let dataPresets = resp.json().presets;
                            return dataPresets;
                        });
                }

                getDataModuleItems(): Observable<any[]> {       
                    return this.http.get('http://localhost:3010/data')
                        .map((resp: Response)=> {
                            let dataModuleItems = resp.json().module_items;
                            return dataModuleItems;
                        });
                }
            }

我的data-all.service

import { Injectable, EventEmitter } from '@angular/core';
    import {Response} from '@angular/http';
    import { ModuleModel } from './model-module';
    import { ModuleItemsModel } from './model-module-items';
    import data from '../data/data-all';
    import { PriceService } from './price.service';
    import { HttpService } from './http-data.service';

    @Injectable()

    export class ModuleDataService {

        constructor(private priceService: PriceService, private httpService: HttpService){
            this.dataMinMaxSum = {minSum: 0, maxSum: 0}
        }

        private currentPopupView: EventEmitter<any> = new EventEmitter<any>();

        private dataModules: ModuleModel[] = this.getDataModules();
        private dataMinMaxSum: {};
        private dataCalculateVariationOrg: any[];
        private dataChangeExecutor: any[];
        subscribe(generatorOrNext?: any, error?: any, complete?: any) {
            this.currentPopupView.subscribe(generatorOrNext, error, complete);
        }

        calculte(){
            return this.priceService.getDataPrice();
        }

        getDataModules(){
            this.httpService.getDataModules().subscribe(((modules)=>{this.dataModules = modules; console.log(this.dataModules);}));
                console.log('dataModules');
                console.log(this.dataModules);
                return this.dataModules;
        }
      ---------------------------------------------------------------------------
    }

我的left-block.component

import { Component, OnInit} from '@angular/core';
    import { ModuleDataService } from '../../service/data-all.service';
    import { ModuleModel } from '../../service/model-module';

    @Component({
        moduleId: module.id,
        selector: 'modules-left-block',
        templateUrl: './modules-left-block.html',
        styleUrls: ['modules-left-block.css']
    })
    export class ModuleLeft implements OnInit{

        modules: ModuleModel[];

        constructor(private modulesAll: ModuleDataService){}


        ngOnInit(){
            this.modules = this.modulesAll.getDataModules();
            console.log("view");
            console.log(this.modulesAll.getDataModules());
        }

        onToggle(module: any){
            this.modulesAll.toggleModules(module);
        }
    }

我的left-block.component.html

<div class="modules-all">
        <div class="modules-all-title">Все модули</div>
        <div class="module-item" *ngFor="let module of modules" [ngClass]="{ 'active': module.completed }" (click)="onToggle(module)">{{module?.title}}</div>

    </div>

在组件中,this.modulesAll.getDataModules()方法只是在没有更新的情况下执行一次(写入console =&gt; undefined),如果有任何想法,请写信,谢谢。

1 个答案:

答案 0 :(得分:1)

此行为是由于.subscribe()方法不等待数据到达而我猜测您已经知道这一点。您遇到的问题是因为您在wron地方.subscribe服务getDataModules()。你不应该subscribe到另一个服务中的服务(在这种情况下是leat)。将subscribe方法移至 left-block.component ,它应该可以正常工作。

&#13;
&#13;
getDataModules() {
  this.httpService.getDataModules().subscribe(((modules) => {
    this.dataModules = modules;
    console.log(this.dataModules);
  }));
  console.log('dataModules');
  console.log(this.dataModules);
  return this.dataModules;
}
&#13;
&#13;
&#13;

应该看起来像这样:

&#13;
&#13;
@Component({
  moduleId: module.id,
  selector: 'modules-left-block',
  templateUrl: './modules-left-block.html',
  styleUrls: ['modules-left-block.css']
})
export class ModuleLeft implements OnInit {

  modules: ModuleModel[] = new ModuleModel();

  constructor(private modulesAll: ModuleDataService, private httpService: HttpService) {}


  ngOnInit() {
    this.getDataModles();
    //this.modules = this.modulesAll.getDataModules();
    console.log("view");
    //console.log(this.modulesAll.getDataModules());
  }

  onToggle(module: any) {
    this.modulesAll.toggleModules(module);
  }

  getDataModules(): void {
    this.httpService.getDataModules().subscribe(((modules) => {
      this.modules = modules;
      console.log(this.dataModules);
    }));
  }

}
&#13;
&#13;
&#13;