IONIC httpclient провайдер, данные исчезают - PullRequest
0 голосов
/ 16 декабря 2018

Я написал этот простой провайдер HTTP:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class GetQueriesProvider {
  constructor(public http: HttpClient) { console.log('Hello GetQueriesProvider'); }

  getRemoteData() {
    return new Promise(resolve => {
      this.http.get('/TJSON/t22.json').subscribe(data => {resolve(data);}, err => {console.log(err);});
    });
  }
}

И вот, компонент, который его использует:

import { Component } from '@angular/core';
import { Sector } from "../../models/sector.models";
import { GetQueriesProvider } from '../../providers';
@Component({ selector: 'app-sector', templateUrl: './sector.html'})

export class SectorComponent  {
  sectors: any;
  constructor(public getDataService: GetQueriesProvider ) {
    this.getData().then((data) => { this.sectors = data; console.log("1: ", this.sectors);});
    console.log("2: ", this.sectors);
  }
  getData()  { return this.getDataService.getRemoteData(); }
  ngOnInit() { }
}

Проблема, которую я не смог решить (и ядумаю, это тривиально) в том, что в «Секторах 1» this.sectors «не определено».

Здесь журнал консоли:

2: undefined

1:
(2) […]
0: Object { area: "Room", domande: (6) […] }
1: Object { area: "FB", domande: (2) […] }
length: 2
<prototype>: Array []

Может кто-нибудь мне помочь?

СПАСИБО!

Ответы [ 2 ]

0 голосов
/ 16 декабря 2018

Я подозревал, что это была проблема синхронизации ... и это так.Эта ссылка сообщает точно мой случай: https://www.joshmorony.com/dealing-with-asynchronous-code-in-ionic/

Так что я думаю, что теперь мне нужно играть с декоратором @output (), чтобы синхронизировать мою страницу

0 голосов
/ 16 декабря 2018

Пожалуйста, измените код компонента на следующий

import { Component } from '@angular/core';
import { DOMANDETEST } from '../../assets/domandeTest';
import { DOMANDEDUMMY } from '../../assets/domandeDummy';
import { Sector } from "../../models/sector.models";
import { GetQueriesProvider } from '../../providers';
import { QuestionsProvider } from '../../providers';

    @Component({
        selector: 'app-sector',
        templateUrl: './sector.html'
    })
    export class SectorComponent {
        sectors: Sector[];

        constructor(public getDataService: GetQueriesProvider, public questionsService: QuestionsProvider) {
            this.sectors = DOMANDEDUMMY;

            this.getData().then((data) => {
                if (data.length < 2) {
                    this.sectors = DOMANDETEST;
                } else {
                    this.sectors = data;
                }

                this.questionsService.set(this.sectors);
            });
        }

        getData() {
            // return this.getDataService.getRemoteData().then(data => {
            //     this.questionsService.set(data);
            //     console.log("Sectors 0: ", this.questionsService.sctrs);
            //     return data;
            // });

            return this.getDataService.getRemoteData();
        }

        ngOnInit() { }
    }
...