简体   繁体   中英

(Angular2) JSON data (http.get()) is undefined, and data is not updated in the component

My http-data.service accepts json for output in the component template. Initially, the console shows that the first few calls are given undefined, and the following calls are already taking json, but also if you check the component, then the component shows that the method that outputs the data to the component is called only once and since the data has not yet arrived it writes undefined , But not updated after the arrival of json. Help please understand why? Thank you

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

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

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

My 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>

In the component this.modulesAll.getDataModules () method is why it is executed only once without updating (write in console => undefined), if there are any thoughts, write, thanks.

This behaviour is due to the .subscribe() method does not wait for the data to arrive and I'm guessing you already know this. The problem you're facing is because, you have .subscribe to the getDataModules() service in the wron place. You shouldn't subscribe to a service in another service (at leat in this case). Move the subscribe method to the left-block.component and it should work.

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

It should look somethig like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM